Call setTimeout without delay

后端 未结 5 1043
闹比i
闹比i 2020-12-05 04:07

Quite often see in JavaScript libraries code like this:

setTimeout(function() {
    ...
}, 0);

I would like to know why use such a wrapper

5条回答
  •  醉酒成梦
    2020-12-05 04:56

    When you want to execute rest of your code without waiting previous one to finish you need to add it in anonymous method passed to setTimeout function. Otherwise your code will wait until previous is done

    Example:

    function callMe()
    {
       for(var i = 0; i < 100000; i++)
         {
           document.title = i;
         }
    } 
    
    var x = 10;
    setTimeout(callMe, 0);
    
    var el = document.getElementById('test-id');
    el.innerHTML = 'Im done before callMe method';
    

    That is the reason I use it.

提交回复
热议问题