简体   繁体   English

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

[英]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). 它基于你只使用1个计时器的假设 (否则,谁知道你清楚哪个计时器?)到目前为止,这还没有造成问题(奇迹,我知道)。

You could wrap it into an object that remembers the timer id: 您可以将其包装到记住计时器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! 免责声明:未经测试 - 抓住这个想法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM