Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is a more elegant way of toggling a javascript timer

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).

like image 383
jason Avatar asked Feb 26 '23 16:02

jason


1 Answers

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!

like image 143
xtofl Avatar answered Mar 01 '23 11:03

xtofl