Javascript setTimeOut真的是异步吗?

时间:2018-01-14 23:55:19

标签: javascript node.js multithreading asynchronous

我正在开发test nodejs应用程序,我想创建100个“线程”,每个使用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');

现在我不理解输出:

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

我期望在executed thread X current counter is Y之间混合executed setTimeOut number Z,为什么它首先似乎将所有调用添加到setTimeOut中,然后才执行它们?即使我将数量设定为1,000,000,这仍然会发生。这看起来不像我预期的行为。

1 个答案:

答案 0 :(得分:5)

<Component { condition ? ...propsA : ...propsB } /> 的来电同步发生。然后运行时有一堆排队的'任务',它可以在以后执行。当超时到期时,运行时可以自由选择这些任务并执行。因此,所有“执行的setTimeOut数字”消息首先显示,然后是“执行的线程......”。