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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With