admin管理员组

文章数量:1434908

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

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

Share Improve this question asked Jul 14, 2010 at 18:58 jasonjason 4,8019 gold badges40 silver badges46 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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!

本文标签: what is a more elegant way of toggling a javascript timerStack Overflow