Will setInterval cause browsers to hang?

大兔子大兔子 提交于 2019-11-26 23:03:48

The reason setInterval is bad is because it will try to execute the code every X MS regardless of what's going on in the thread. So if you have:

setInterval( complexFunction, 1 ); // complexFunction takes >1 MS to complete

...you may end up with setInterval trying to re-execute several times before even its own code is complete! However, you can use setTimeout similarly and avoid this problem:

setTimeout( complexFunction, 1 );

function complexFunction() {
  // complex code
  setTimeout( complexFunction, 1 );
}

...now complexFunction will only call itself again once its own code is complete, so if its own code takes longer than 1 MS to complete you won't have any backlog to deal with like you would with setInterval

it always better to use setTimeout in a loop so you know exactly when to continue timing:

foo();
function foo(){

   setTimeout (function(){
      foo = 'bar_' + i++;
      foo();
     }, 1 );

} 

otherwise as you said above, the browser will have to catch up and since ur loop is in infinitum, it might not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!