javascript - Using multiple instances of setInterval -


i have jsfiddle here: http://jsfiddle.net/dztga/22/

the goal: essentially, i'm trying have 2 discrete timers on same page can destroyed , re-created on mouseover/mouseout (pause), or on manual progression (restart).

the problem: jsfiddle's single timer illustrate when click "stop timer", setinterval (stored in variable t) seems have multiple instances albeit being destroyed clearinterval(t). becomes apparent when click "restart timer" , seems have 2+ independent timers illustrated quick increment.

a caveat: have done research on can, because i'll having 2 different sliders on page, can't use "clear timers" methods, tried storing each in variable.

i hope that's clear. view.

to fix current issue: add clearinterval(window.t) @ onclick function of reset button.

a method able have multiple timers. requires structure, though.
fiddle (6 timers!): http://jsfiddle.net/dztga/27/

(function(){ //anonymous function, not leak variables 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 , 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)();     }); })(); 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -