setTimeout or setInterval?

前端 未结 19 3233
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    2020-11-21 05:24

    I find the setTimeout method easier to use if you want to cancel the timeout:

    function myTimeoutFunction() {
       doStuff();
       if (stillrunning) {
          setTimeout(myTimeoutFunction, 1000);
       }
    }
    
    myTimeoutFunction();
    

    Also, if something would go wrong in the function it will just stop repeating at the first time error, instead of repeating the error every second.

提交回复
热议问题