Why Would I Ever Use setTimeout With a 0ms Delay?
0 delay === instantly. But that’s not what happens. Let’s examine a simple example where I log a few values to the console with a setTimeout thrown in there to see what happens.
console.log(1); console.log(2); setTimeout(function() console.log(3); }, 0); console.log(4);
Naturally, I’d expect the numbers 1, 2, 3, 4 to log to the console in order. Instead, what logs is 1, 2, 4, 3. Why does this happen?
The Singlethreaded Problem