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 badges1 Answer
Reset to default 9You 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
版权声明:本文标题:what is a more elegant way of toggling a javascript timer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745643340a2667988.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论