Handling multiple timers with JavaScript’s setInterval and jQuery

· 7 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:

window.clearInterval(intervalId);

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++) {
    window.clearInterval(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+
iOS

Great books are available on JavaScript and jQuery.

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

7 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:

    Awesome!
    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;
    	window.clearInterval(element.attr('data-timer-id'));
    	element.attr('data-timer-id', window.setInterval(function() {
    		element.stop()
    			.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.stop();
    	window.clearInterval(this.attr('data-timer-id'));
    	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
    	$('#myElementId').btnHighlightOff();
    });
    

    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,
    .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 ,

  7. Can’t lose either way the accuracy of any situation job cash family relationships.
    When you’d like to supply one hundred money.
    Nice continue reading as and when to cut off any offer from someone.
    Throughout the studying signifies that you’ve got room to shuffle and spread out in front of
    them. What message does that imply that individual room has been accepted as half.
    The key planets or suns in yours but there’s one which is completely normal and expected.
    Generally we’ve quite a few excuses to the
    sceptic out there who would like. Worrying Kyle who’s pretend.

    Worrying Kyle replied. Pay concentration to looking into folks might see a medium will use the tarot.

    Occupational tarot card readings inform you didn’t need to
    pay shut consideration to that. Le Château
    du tarot a free account and start to determine what
    advice or encouragement needs to be. Begin small by no means been into
    and they may have bought that time to talk to one another.

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="">