[英]Is Javascript setTimeOut truly async?
我正在開發測試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 setTimeOut number Z
之間混合executed thread X current counter is Y
,為什么它似乎首先似乎將所有調用添加到setTimeOut中,然后才執行它們? 即使當我將計數設置為1,000,000時,這種情況仍在發生。 在我看來,這似乎不是預期的行為。
對setTimeout
的調用是同步發生的。 然后,運行時就會排隊等待一堆“任務”,以便以后可以執行。 超時到期后,這些任務可以由運行時自由選擇並執行。 因此,所有“已執行setTimeOut號”消息首先出現,然后是“已執行線程...”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.