最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

what is a more elegant way of toggling a javascript timer - Stack Overflow

matteradmin3PV0评论

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!

Post a comment

comment list (0)

  1. No comments so far