JavaScript setTimeOut是否真正异步? [英] Is Javascript setTimeOut truly async?
问题描述
我正在开发测试nodejs应用程序,我想创建100个线程",每个线程都使用setTimeOut在某个随机时间执行.
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
我期望在executed setTimeOut number Z
之间混入executed thread X current counter is Y
,为什么它似乎首先将所有调用添加到setTimeOut中,然后才执行它们?即使当我将计数设置为1,000,000时,这种情况仍在发生.在我看来,这似乎不是预期的行为.
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.
推荐答案
对setTimeout
的调用是同步发生的.这样,运行时就会排队等待一堆任务",以便以后可以执行.超时到期时,这些任务可以由运行时自由选择并执行.因此,所有已执行的setTimeOut号"消息首先出现,然后是已执行的线程...".
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...'.
这篇关于JavaScript setTimeOut是否真正异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!