Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why setTimeout code blocked?

function test(){
  setTimeout(function(){
    var now=new Date();
    while((new Date()).getTime() < now.getTime()+5000){ }
    console.log('p')
  }, 0);
}

test();
test(); //it takes 10 seconds,the second test function runs after the first finished.

can somebody explain to me how it works?

like image 676
lx1412 Avatar asked Sep 18 '16 06:09

lx1412


1 Answers

This is happening because, whenever you pass a function inside of setTimeout and call it, the passed function will be pushed into the callBack queue based on the supplied delay in milliseconds. The functions inside of callBack queue will be executed one by one in the order they have pushed. So here in your case, you are blocking the code flow of function which is present inside of callBack queue, by running a while loop. Hence the second call of test is taking 10 seconds to execute.

test(); //call 1
callBack queue ---->  [function(){ while(){} }]

test(); //call 2
callBack queue ---->  [function(){ while(){} }, function(){ while(){} }]

Note: Call back queue will start its execution when there is nothing in the call stack to execute.

Best read for this, Event Loop.

like image 172
Rajaprabhu Aravindasamy Avatar answered Sep 28 '22 07:09

Rajaprabhu Aravindasamy