什么是切换javascript计时器的更优雅的方式

jas*_*son 4 javascript timer

我制作并使用了这个,但我知道更好的方法:

function toggle_timer()
{
    if(timer_id > 0){
        clearTimeout(timer_id);
        timer_id=0;
    }

    else timer_id = setInterval("go()", interv);
}  
Run Code Online (Sandbox Code Playgroud)

它基于你只使用1个计时器的假设(否则,谁知道你清楚哪个计时器?)到目前为止,这还没有造成问题(奇迹,我知道).

xto*_*ofl 8

您可以将其包装到记住计时器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();
Run Code Online (Sandbox Code Playgroud)

免责声明:未经测试 - 抓住这个想法!