Handling multiple timers with JavaScript’s setInterval and jQuery

· 6 Comments · in JavaScript, jQuery

For a recent project I needed to create a slideshow with auto play capability. To achieve this I used JavaScript’s setInterval to rotate the slides every 15 seconds.

intervalId = window.setInterval("moveSlide()",15000);

To stop animation the timer needed to be cleared. The conventional way is:


All well and good if you only have one timer on a page.

But what if you need to have multiple timers? Using the above syntax will only clear one timer of variable “intervalId”. We need to be able to target specific timers. In my opinion, the topic of JavaScript timers has always seemed a bit fuzzy. This is my attempt to give it some clarity.

Storing a specific timer id
When a timer is created with setInterval, it returns a unique number that can be used to target that timer. You only need to store it. For this I used jQuery to add the value as a data attribute on the associated slideshow element. This allowed me to create an association between the specific slideshow and timer. You can store it a number of other ways to fit your needs.

intervalId = window.setInterval("moveSlide()",15000);
$(slideshowElement).attr( "data-timer-id",intervalId );

Clearing a specific timer id
To clear a specific timer, you must use it’s id – not the variable name that created it. Now when I need to clear a specific timer I can target it like so:

window.clearInterval( $(slideshowElement).attr("data-timer-id") );

Clearing all running timers
Unique timer ids are not created randomly, they are created in sequential order. We can take advantage of this to clear all running timers. Create a setInterval that calls an anonymous function, whose resulting timer id value will be greater than any other timer previously created. We run a loop to clear all timers with a lesser or equal value.

var newTimerId = window.setInterval("function(){}");
for (var i = 0 ; i <= newTimerId; i++) {

This logic should also work with setTimeout, though I have not tested it.

See the full working example here.

Tested in:
jQuery version 1.7.2
FF 3.6+, Safari, Chrome, IE8+

Great books are available on JavaScript and jQuery.

This entry was posted in JavaScript, jQuery and tagged , .
Bookmark the permalink.

6 Responses to Handling multiple timers with JavaScript’s setInterval and jQuery

  1. Pingback: Banner ad animation with jQuery | The Blog of Clarke Ulmer

  2. AK says:

    Dude you are genious, it worked very well for me.

  3. Son Goku says:

    Storing the interval id as attribute value is perfect! Just what is was looking for. You Sir earned my respect. Let me share my work: jQuery prototype function with call. Activates animation on element and stops it when needed. Working under jQuery 3.1.1, jQuery color plugin just to animate background color and font color.

     * Sets interval for element.
     * @param {number} duration
     * @param {number} interval
     * @return {void}
    $.fn.btnHighlightOn = function(duration, interval) {
    	var originalBg = 'transparent';
    	var originalColor = '#fff';
    	var highlightBg = '#fff';
    	var highlightColor = '#000';
    	var animateMs = duration || 1500;
    	var interval = interval || 2500;
    	//inside the interval function 'this' 
    	//is referred to something else and not our element
    	var element = this;
    	element.attr('data-timer-id', window.setInterval(function() {
    			.animate({backgroundColor: highlightBg, color: highlightColor}, (animateMs / 4))
    			.animate({backgroundColor: originalBg, color: originalColor}, (animateMs / 4))
    			.animate({backgroundColor: highlightBg, color: highlightColor}, (animateMs / 4))
    			.animate({backgroundColor: originalBg, color: originalColor}, (animateMs / 4));
    	}, interval));
     * Unsets interval of element.
     * @return {void}
    $.fn.btnHighlightOff = function() {
    	this.attr('data-timer-id', 0);
    //calls it when page loads, but can be put inside a function and called on any dom event
    //this is the proper way calling on window onload!
    $(window).on('load', function() {
    	//start animation
    	$('#myElementId').btnHighlightOn(1500, 2500);
    	//stop animation

    Just have an HTML element like:

    <p><button type="button" id="myElementId" class="btn-outline btn-outline-dark btn-outline-md">Button</button></p>
    .btn-outline {
    	background-image: none;
    	position: relative;
    	display: inline-block;
    	text-transform: uppercase;
    	border-width: 1px;
    	border-style: solid;
    	border-radius: 2px;
    	vertical-align: top;
    	text-align: center;
    	text-overflow: ellipsis;
    	cursor: pointer;
    .btn-outline:disabled:active {
    	background: #eee;
    	color: #ddd;
    	border: 1px solid #ddd;
    .btn-outline-md {
    	padding: 0 12px;
    	min-width: 52px;
    	min-height: 47px;
    	line-height: 42px;
    	font-size: 15px;
    .btn-outline-dark {
    	color: #444;
    	background-color: transparent;
    	border: 1px solid #444;
    .btn-outline-dark:active {
    	color: #fff;
    	background-color: #444;
  4. 86Cheri says:

    I see you don’t monetize your blog, don’t
    waste your traffic, you can earn additional bucks every month because
    you’ve got high quality content. If you want to know how to make extra money,
    search for: best adsense alternative Wrastain’s tools

  5. AC says:

    Clearing intervals in a loop, as described in “Clearing all running timers” is as stupid as it can get. One of the worst antipatterns I could imagine, unless you are *highly* aware of what you’re doing. There might be many different parts of your app, that make use of intervals and their behaviour will be completely broken by clearing all intervals. And debugging them later? Have fun.

    Bottom line: *never* clear intervals other then the one you have personally created and saved its id.

  6. Sumeet Mathew says:

    Thanks for the help , it really saved my day ,

Leave a Reply

Your email address will not be published. Required fields are marked *


To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">