I'm trying to understand which parts of javascript are synchronous and which are asynchronous.
My question is, in the following code why does it alert 16384 before it alerts 1 when the loop takes waay longer than 1ms ?
Demo
setTimeout(function () {
alert(1)
}, 1)
for (i = 0; i < 16384; i++) {
for (j = 0; j < 16384; j++) {}
}
alert(j)
JavaScript is generally single-threaded. This means that your setTimeout callback can't happen until you relinquish control of the thread. Your double for loop executes and shows its alert before the setTimeout alert is allowed to happen.
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