Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronicity of javascript

Tags:

javascript

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)
like image 632
andrew Avatar asked Jun 11 '26 15:06

andrew


1 Answers

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.

like image 148
JLRishe Avatar answered Jun 13 '26 06:06

JLRishe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!