0

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.

4
  • Your creation of setTimeOuts is not asynchronous. Async just means that it's allowed to be run asynchronously. It doesn't necessarily require it unless you specifically sleep the thread. Commented Jan 14, 2018 at 23:59
  • yes, I understand, I call setTimeOut in sync one after another. but by the time I call say setTimeOut the millionth time, Id expect at least some of the timed functions to have been executed. why this is not happening? Commented Jan 15, 2018 at 0:02
  • The loop sets all the functions sequentially in a loop, they're called more or less randomly, but they all have a closure to the global counter, which counts sequentially. Commented Jan 15, 2018 at 0:04
  • 1
    @TomášNavara Javascript only have one thread. Therefore the for loop is executed first. Nothing else happens until the for-loop it finished. When there is nothing else happening, then the engine will check if there is something that has timed out, and if so run it. Commented Jan 15, 2018 at 0:05

1 Answer 1

5

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...'.

Sign up to request clarification or add additional context in comments.

4 Comments

but if I use counter = 10000000 I would expect to see at least SOME of the timed function's outputs mixed between that. As that is the point of setTimeOut, no? It should start the timer when it is called, and this timer for sure will tick before the whole loop of 10000000 is looped through
@TomášNavara - no, Javascript is single-threaded (unless you're using a specific threading framework, e.g. web workers). Your async tasks can't execute until the existing foreground task finishes. Specifically, your tasks can be executed at any time after the timeout you specify expires, but are not guaranteed to immediately start when it does because some other task may need to complete first.
so if I set a timer and then do some things that take 1min to finish, then timer will tick in 1min+ timeout since placed?
@TomášNavara—yes, setTimeout puts things on a queue that can't run until the current thread completes. And none of the timeouts will be executed while some other task is running, they must wait at least the allotted time, then find an opportunity to run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.