setTimeout behaviour with blocking code

后端 未结 4 1425
无人及你
无人及你 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:21

    When you run the busy-waiting loop after the setTimeout call, you don't let time for your "Yo!" to print out, because the Javascript runtime is busy with your loop (actualy the empty statement also makes it busy because of continues evaulaation of the loop condition).

    You should always avoid such a busy-waiting loop, because until that finishes, nothing else can be called or run in that window.

提交回复
热议问题