setTimeout behaviour with blocking code

后端 未结 4 1444
无人及你
无人及你 2020-11-29 08:01

This is my test code (fiddle here):

console.log(\'Before wait\');
setTimeout(function () { console.log(\'Yo!\'); }, 1000);
var start = Date.now();
while (Dat         


        
4条回答
  •  余生分开走
    2020-11-29 08:32

    The delay of setTimeout is relative to the exact point in time when it is called. It expires while you are still busy waiting. So it will be performed at the next instant where the control goes back into the event loop.

    Edit:

    The spec is a bit vague in this point, but I guess it's the intended and only straightforward interpretation:

    setTimeout(function, milliseconds)

    This method calls the function once after a specified number of milliseconds elapses, until canceled by a call to clearTimeout. The methods returns a timerID which may be used in a subsequent call to clearTimeout to cancel the interval.

提交回复
热议问题