Using multiple instances of setInterval

12,402

Solution 1

To fix your current issue: Add clearInterval(window.t) at the onclick function of the reset button.

A method to be able to have multiple timers. This requires a certain structure, though.
Fiddle (6 timers!): http://jsfiddle.net/dztGA/27/

(function(){ //Anonymous function, to not leak variables to the global scope
    var defaultSpeed = 3000; //Used when missing
    var timerSpeed = [500, 1000, 2000, 4000, 8000];

    var intervals = [];
    function increase(i){
        return function(){
            var elem = $("#count"+i);
            elem.text(parseFloat(elem.text()) + 1);
        }
    }
    function clear(i){
        return function(){
            clearInterval(intervals[i]);
        }
    }
    function restart(i){ //Start AND restart
        return function(){
            clear(i)();
            increase(i)();
            intervals[i] = setInterval(increase(i), timerSpeed[i]||defaultSpeed);
        }
    }
    // Manual increment
    $('input[name=increment]').each(function(i){
        $(this).click(function(){
            restart(i)();
            increase(i)();
        });
    });

    // Clear timer on "Clear"
    $('input[name=clear]').each(function(i) {
        $(this).click(clear(i));
    });

    // Restart timer on "Restart"
    $('input[name=reset]').each(function(i) {
        $(this).click(restart(i));

        //Optionally, activate each timer:
        increase(i)();
    });
})();

Solution 2

// Clear timer on "Clear"
$('input[name=clear]').click(function() {
    window.clearInterval(t);
});

should be

// Clear timer on "Clear"
$('input[name=clear]').click(function() {
    window.clearInterval(window.t);
});

because this is the input not Window

Share:
12,402
Morgan Delaney
Author by

Morgan Delaney

I ♥ Stack Overflow.

Updated on June 14, 2022

Comments

  • Morgan Delaney
    Morgan Delaney almost 2 years

    I have a jsFiddle here: http://jsfiddle.net/dztGA/22/

    The goal: Essentially, I'm trying to have 2 discrete timers on the same page that can be destroyed and re-created on mouseover/mouseout (pause), or on manual progression (restart).

    The problem: What my jsFiddle's single timer will illustrate is that when I click "Stop Timer", my setInterval (stored in variable t) seems to have multiple instances albeit being destroyed with clearInterval(t). This becomes apparent when I click "Restart Timer" and it seems to have 2+ independent timers as illustrated by the quick increment.

    A caveat: I have done as much research on SO as I can, but because I'll be having 2 different sliders on the page, I can't use any "clear all timers" methods, so I tried storing each in a variable.

    I hope that's clear. Thanks for the view.