setTimeOut() or setInterval() . 4 methods to apply same thing. which is best?

后端 未结 3 503
自闭症患者
自闭症患者 2020-12-18 06:09

I am displaying a countdown watch with respect to a given endtime.

although its working perfect but i want to know which is best methods to apply.

below is m

3条回答
  •  鱼传尺愫
    2020-12-18 07:08

    The benefit of using #1 over #2 is that the window reference removes the chance of a scope variable overwriting setInterval.

    // When out of global scope...
    function setInterval() {
    
    }
    
    window.setInterval(foo, 100); // still calls the "correct" setInterval
    

    There's no difference between wrapping the call to countdown in a function (#1, #2). #2 gives you greater flexibility as you can also call other functions/ pass arguments etc (although it's obviously trivial to swap from #1 to #2 if this becomes the case).

    #4 saves you having to declare a function clockStart, other than that, it's the same as #3.

    Use clearTimeout if you used setTimeout, and clearInterval if you used setInterval...

    You should also be aware of how setTimeout and setInterval work differently. There's an amazing answer here which explains that...

    As for what I'd use? I'd use #2.

提交回复
热议问题