Why is setTimeout 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 someone explain to me how this works?

+6
source share
2 answers

This is because whenever you pass a function inside setTimeout and call it, the passed function will be placed in the callBack based on the given delay in milliseconds. The functions within the callBack queue will be executed one after another in the order in which they were clicked. So, here, in your case, you block the flow of function code that is present inside the callBack queue by running the while . Therefore, the second test call takes 10 seconds to complete.

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

Note: the callback queue will start when nothing has been executed in the call stack.

It’s best to read this, Event Loop .

+5
source

If you need a non-blocking implementation, you should replace your synchronous while asynchronous recursion:

 function test(x){ setTimeout(function loop(now) { (new Date()).getTime() < now.getTime()+2000 ? setTimeout(loop, 0, now) : console.log('p', x); },0, new Date()) } test(1); test(2); 
+2
source

All Articles