setTimeout or setInterval?

前端 未结 19 3519
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:59

As far as I can tell, these two pieces of javascript behave the same way:

Option A:

function myTimeoutFunction()
{
    doStuff();
           


        
19条回答
  •  半阙折子戏
    2020-11-21 05:26

    The setInterval makes it easier to cancel future execution of your code. If you use setTimeout, you must keep track of the timer id in case you wish to cancel it later on.

    var timerId = null;
    function myTimeoutFunction()
    {
        doStuff();
        timerId = setTimeout(myTimeoutFunction, 1000);
    }
    
    myTimeoutFunction();
    
    // later on...
    clearTimeout(timerId);
    

    versus

    function myTimeoutFunction()
    {
        doStuff();
    }
    
    myTimeoutFunction();
    var timerId = setInterval(myTimeoutFunction, 1000);
    
    // later on...
    clearInterval(timerId);
    

提交回复
热议问题