Handling multiple timers with JavaScript’s setInterval and jQuery

· 4 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.

4 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

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