In JavaScript, setTimeout(callback, delay)
means "call callback
after delay
milliseconds". But what if delay
is 0
? Should it call callback
right away?
I am confused because of what I see when I run the following code:
setTimeout(function() {
console.log('AAA');
}, 0); // Call this in 0 milliseconds
for (i = 0; i < 1000; i++) {
console.log('BBB');
}
for (i = 0; i < 1000; i++) {
console.log('CCC');
}
for (i = 0; i < 1000; i++) {
console.log('DDD');
}
for (i = 0; i < 1000; i++) {
console.log('EEE');
}
This logs the following to the console:
I expected to see AAA
logged much sooner than that. There was time to execute 4000 other calls to console.log
before a function which should have been called immediately.
Can someone explain what setTimeout
is doing when the delay is set to 0 milliseconds?