I made and use this one, but I know theres better ways :
function toggle_timer()
{
if(timer_id > 0){
clearTimeout(timer_id);
timer_id=0;
}
else timer_id = setInterval("go()", interv);
}
Its based on the assumption that youll only use 1 timer (otherwise, who knows which timer youll clear?) So far this hasnt caused a problem (miracles, I know).
You could wrap it into an object that remembers the timer id:
function timer( millis_, f_ ) {
return {
f: f_,
millis: millis_,
toggle: function(){
if( this.id > 0 ) clear();
else start();
},
clear: function(){ clearInterval( this.id ); this.id=0; },
start: function(){ this.id=setInterval( this.f, this.millis ); }
};
}
var t1=timer(1000, function(){alert("1000");} );
var t2=timer(10000, function(){ alert("a long time");});
t1.toggle();
t2.toggle();
Disclaimer: untested - grab the idea!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With