Is Javascript setTimeOut truly async?

六眼飞鱼酱① 提交于 2020-01-25 07:48:13

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/48255366/is-javascript-settimeout-truly-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!