Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple instances of setInterval

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.

like image 600
Morgan Delaney Avatar asked Jan 19 '23 12:01

Morgan Delaney


1 Answers

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)();
    });
})();
like image 78
Rob W Avatar answered Jan 29 '23 00:01

Rob W