gpt4 book ai didi

javascript - Javascript setTimeOut 真的是异步的吗?

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:45 24 4
gpt4 key购买 nike

我正在开发测试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

我期望的是执行的线程X当前计数器是Y执行的setTimeOut数字Z之间的混合,为什么它首先似乎将所有调用添加到setTimeOut中,然后才执行它们?即使我将计数设置为 1,000,000,这种情况仍然会发生。对我来说,这看起来不像是预期的行为。

最佳答案

setTimeout 的调用是同步发生的。然后,运行时会将一堆“任务”排队,以便稍后执行。当超时到期时,这些任务可以由运行时自由拾取并执行。因此,您的所有“执行的 setTimeOut number”消息首先出现,然后是您的“执行的线程...”。

关于javascript - Javascript setTimeOut 真的是异步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com