andrew
andrew

Reputation: 9583

Synchronicity of 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)

Upvotes: 3

Views: 577

Answers (2)

Quentin
Quentin

Reputation: 944113

The JS engine won't check to see if any functions are waiting for a timeout to finish until the event loop is free.

i.e. It is too busy running your nested for loops to check.

When it has finished running those loops, it checks, discovers that the timeout is overdue and runs it immediately.

Upvotes: 4

JLRishe
JLRishe

Reputation: 101738

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.

Upvotes: 7

Related Questions