Using multiple instances of setInterval

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

Purpose:. Essentially, I'm trying to have 2 discrete timers on the same page that can be destroyed and re-created using the mouse / mouse (pause) or manual progression (reload).

Problem: What my single jsFiddle timer illustrates is that when I click Stop Timer, my setInterval (stored in variable t) seems to have multiple instances, although it is destroyed using clearInterval (t). This becomes apparent when I click "Restart timer" and it seems to have 2+ independent timers, as shown by fast increment.

Disclaimer: I have done as much SO research as I can, but because I will have 2 different sliders per page, I cannot use the β€œclear all timers” methods, so I tried to save them in a variable.

I hope this is clear. Thanks for the submission.

+4
source share
2 answers

To fix your current problem: add clearInterval(window.t) to the onclick function of the reset button.

A method that allows you to have multiple timers . This requires a certain structure. 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)(); }); })(); 
+8
source
 // Clear timer on "Clear" $('input[name=clear]').click(function() { window.clearInterval(t); }); 

it should be

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

since this is not a Window input

+2
source

All Articles