setTimeout or setInterval?

前端 未结 19 3201
佛祖请我去吃肉
佛祖请我去吃肉 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:23

    When you run some function inside setInterval, which works more time than timeout-> the browser will be stuck.

    - E.g., doStuff() takes 1500 sec. to be execute and you do: setInterval(doStuff, 1000);
    1) Browser run doStuff() which takes 1.5 sec. to be executed;
    2) After ~1 second it tries to run doStuff() again. But previous doStuff() is still executed-> so browser adds this run to the queue (to run after first is done).
    3,4,..) The same adding to the queue of execution for next iterations, but doStuff() from previous are still in progress...
    As the result- the browser is stuck.

    To prevent this behavior, the best way is to run setTimeout inside setTimeout to emulate setInterval.
    To correct timeouts between setTimeout calls, you can use self-correcting alternative to JavaScript's setInterval technique.

提交回复
热议问题