Will setInterval cause browsers to hang?

前端 未结 2 1609
耶瑟儿~
耶瑟儿~ 2020-11-28 15:14

A couple years ago I was warned against using setInterval for long periods of time as it supposedly would cause the browser to hang if the called function ran l

相关标签:
2条回答
  • 2020-11-28 15:41

    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

    0 讨论(0)
  • 2020-11-28 15:44

    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.

    0 讨论(0)
提交回复
热议问题