michnovka
michnovka

Reputation: 3419

Is Javascript setTimeOut truly async?

I am developing test nodejs app, I want to create 100 "threads", each executed at some random time using setTimeOut.

let count = 10;
let counter = 0;

for(let i = 0; i < count; i++) {

    // call the rest of the code and have it execute after 3 seconds
    setTimeout((async () => {
        counter++;

        console.log('executed thread',i, 'current counter is',counter);

        if(counter === count){
            console.log('all processed');
        }


    }), Math.random()*10);

    console.log('executed setTimeOut number ',i);

}

console.log('main thread done, awaiting async');

Now what I dont understand is output:

executed setTimeOut number  0
executed setTimeOut number  1
executed setTimeOut number  2
executed setTimeOut number  3
executed setTimeOut number  4
executed setTimeOut number  5
executed setTimeOut number  6
executed setTimeOut number  7
executed setTimeOut number  8
executed setTimeOut number  9
main thread done, awaiting async
executed thread 5 current counter is 1
executed thread 1 current counter is 2
executed thread 4 current counter is 3
executed thread 9 current counter is 4
executed thread 6 current counter is 5
executed thread 2 current counter is 6
executed thread 3 current counter is 7
executed thread 8 current counter is 8
executed thread 0 current counter is 9
executed thread 7 current counter is 10
all processed

What I would expect is mixed executed thread X current counter is Y between the executed setTimeOut number Z, why does it first seem to add all calls into setTimeOut and only after that execute them? Even when I set count to 1,000,000 this is still happening. That does not look like an expected behavior to me.

Upvotes: 0

Views: 650

Answers (1)

Alex Taylor
Alex Taylor

Reputation: 8853

The calls to setTimeout happen synchronously. The runtime then has a bunch of 'tasks' queued up that it can execute at a later time. When your timeout expires, those tasks are free to be picked up by the runtime and executed. Hence all your 'executed setTimeOut number' messages appear first, then your 'executed thread...'.

Upvotes: 5

Related Questions