views:

51

answers:

1

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

+7  A: 

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!

xtofl
damn, that is nice. Sidenote : everyones coding ability on stackoverflow is outstanding. I feel like such a noob lol, albeit a noob in a very fun playground. Again, tyvm :-)
jason
+1 - great example of adding value added services on top of a very simple API.
Anurag