歡迎光臨我的博客拓跋的前端客棧,如果您發現我文章中存在錯誤,請盡情向我吐槽,大家一起學習一起進步φ(>ω<*)
1. 初探 --- setTimeout()的那些事兒
相信很多人在初學JavaScript的時候都遇到過類似的代碼:
// part1
console.log(1);
setTimeout(function(){
console.log(2);
},100);
console.log(3);
console.log(4);
// part2
console.log(1);
setTimeout(function(){
console.log(2);
},0);
console.log(3);
console.log(4);
萌新們看到這個,肯定覺得很簡單。part1輸出順序是1,3,4,2;part2輸出順序是1,2,3,4嘛。顯而易見,part1中在打印2的時候延遲了100ms,所以被放到了隊列的尾端執行,理所當然的最后輸出;part2中雖然調用了setTimeout函數,但是延遲設置為0ms,實際上并未延遲,因此應該立即執行,所以輸出順序應該是1,2,3,4。
看到這里,很多人應該都知道了,上面的說法實際上是錯誤的。
setTimeout(fn,0)的含義是,指定某個任務在主線程最早可得的空閑時間執行,也就是說,盡可能早得執行。它在"任務隊列"的尾部添加一個事件,因此要等到同步任務和"任務隊列"現有的事件都處理完,才會得到執行。
上面的這段文字摘自阮一峰的博客,即使你的延遲設定的是0,setTimeout仍然會將你的函數給放到隊列最尾端,等你的當前任務執行完畢以后,才會去執行該函數。
2. 深入 --- setTimeout()和Promise同場競技時是什么樣呢?
眾所周知,Promise是ES6發布的一種非常流行的異步實現方案,當Promise和setTimeout同時出現在一段代碼中,他們的執行順序是什么樣子的呢?請看下面這段代碼:
setTimeout(function(){
console.log(1)
},0);
new Promise(function(resolve){
console.log(2)
for( var i=100000 ; i>0 ; i-- ){
i==1 && resolve()
}
console.log(3)
}).then(function(){
console.log(4)
});
console.log(5);
如果按照正常邏輯分析,應該是這樣的:
- 當運行到setTimeout時,會把setTimeout的回調函數console.log(1)放到任務隊列里去,然后繼續向下執行。
- 接下來會遇到一個Promise。首先執行打印console.log(2),然后執行for循環,即時for循環要累加到10萬,也是在執行棧里面,等待for循環執行完畢以后,將Promise的狀態從fulfilled切換到resolve,隨后把要執行的回調函數,也就是then里面的console.log(4)推到任務隊列里面去。接下來馬上執行馬上console.log(3)。
- 然后出Promise,還剩一個同步的console.log(5),直接打印。這樣第一輪下來,已經依次打印了2,3,5。
- 然后再讀取任務隊列,任務隊列里還剩console.log(1)和console.log(4),因為任務隊列是隊列嘛,肯定遵循的先進先出的策略,因此更早入列的setTimeout()的回調函數先執行,打印1,最后剩下Promise的回調,打印4。
因此一通分析下來,得到的打印結果是2,3,5,1,4。那我們實際試一下呢?
2
3
5
4
1
啊嘞嘞?跟我們一開始想象的貌似有點不一樣啊!是什么原因導致了原本應該在setTimeout回調后面的Promise的回調反而跑到前面去執行了呢?
為了搞清這個問題,我專門去翻閱了一下資料,首先找到了Promises/A+標準里面提到:
Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such as setTimeout or setImmediate, or with a “micro-task” mechanism such as MutationObserver or process.nextTick.Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.
這里提到了micro-task和macro-task這兩個概念,并分別列舉了兩種情況:setTimeout和setImmediate屬性macro-task,MutationObserver和process.nextTick屬性micro-task。但并沒有進一步的詳述,于是我以此為線索進一步搜索資料,找到stackoverflow上的一個問答,終于讓我的疑惑得到解決。
macrotasks和microtasks的劃分:
macrotasks:
- setTimeout
- setInterval
- setImmediate
- requestAnimationFrame
- I/O
- UI rendering
microtasks:
- process.nextTick
- Promises
- Object.observe
- MutationObserver
那我們上面提到的任務隊列到底是什么呢?跟macrotasks和microtasks有什么聯系呢?
- An event loop has one or more task queues.(task queue is macrotask queue)
- Each event loop has a microtask queue.
- task queue = macrotask queue != microtask queue
- a task may be pushed into macrotask queue,or microtask queue
- when a task is pushed into a queue(micro/macro),we mean preparing work is finished,so the task can be executed now.
翻譯一下就是:
- 一個事件循環有一個或者多個任務隊列;
- 每個事件循環都有一個microtask隊列
- macrotask隊列就是我們常說的任務隊列,microtask隊列不是任務隊列
- 一個任務可以被放入到macrotask隊列,也可以放入microtask隊列
- 當一個任務被放入microtask或者macrotask隊列后,準備工作就已經結束,這時候可以開始執行任務了。
可見,setTimeout和Promises不是同一類的任務,處理方式應該會有區別,具體的處理方式有什么不同呢?我從這篇文章里找到了下面這段話:
Microtasks are usually scheduled for things that should happen straight after the currently executing script, such as reacting to a batch of actions, or to make something async without taking the penalty of a whole new task. The microtask queue is processed after callbacks as long as no other JavaScript is mid-execution, and at the end of each task. Any additional microtasks queued during microtasks are added to the end of the queue and also processed. Microtasks include mutation observer callbacks, and as in the above example, promise callbacks.
通俗的解釋一下,microtasks的作用是用來調度應在當前執行的腳本執行結束后立即執行的任務。 例如響應事件、或者異步操作,以避免付出額外的一個task的費用。
microtask會在兩種情況下執行:
- 任務隊列(macrotask = task queue)回調后執行,前提條件是當前沒有其他執行中的代碼。
- 每個task末尾執行。
另外在處理microtask期間,如果有新添加的microtasks,也會被添加到隊列的末尾并執行。
也就是說執行順序是:
開始 -> 取task queue第一個task執行 -> 取microtask全部任務依次執行 -> 取task queue下一個任務執行 -> 再次取出microtask全部任務執行 -> ... 這樣循環往復
Once a promise settles, or if it has already settled, it queues a microtask for its reactionary callbacks. This ensures promise callbacks are async even if the promise has already settled. So calling .then(yey, nay) against a settled promise immediately queues a microtask. This is why promise1 and promise2 are logged after script end, as the currently running script must finish before microtasks are handled. promise1 and promise2 are logged before setTimeout, as microtasks always happen before the next task.
Promise一旦狀態置為完成態,便為其回調(.then內的函數)安排一個microtask。
接下來我們看回我們上面的代碼
setTimeout(function(){
console.log(1)
},0);
new Promise(function(resolve){
console.log(2)
for( var i=100000 ; i>0 ; i-- ){
i==1 && resolve()
}
console.log(3)
}).then(function(){
console.log(4)
});
console.log(5);
按照上面的規則重新分析一遍:
- 當運行到setTimeout時,會把setTimeout的回調函數console.log(1)放到任務隊列里去,然后繼續向下執行。
- 接下來會遇到一個Promise。首先執行打印console.log(2),然后執行for循環,即時for循環要累加到10萬,也是在執行棧里面,等待for循環執行完畢以后,將Promise的狀態從fulfilled切換到resolve,隨后把要執行的回調函數,也就是then里面的console.log(4)推到microtask里面去。接下來馬上執行馬上console.log(3)。
- 然后出Promise,還剩一個同步的console.log(5),直接打印。這樣第一輪下來,已經依次打印了2,3,5。
- 現在第一輪任務隊列已經執行完畢,沒有正在執行的代碼。符合上面講的microtask執行條件,因此會將microtask中的任務優先執行,因此執行console.log(4)
- 最后還剩macrotask里的setTimeout放入的函數console.log(1)最后執行。
如此分析輸出順序是:
2
3
5
4
1
看吧,這次分析對了呢ヾ(?°?°?)??
3. 總結和參考資料
microtask和macrotask看起來容易混淆,實際上還是很好區分的。macrotask就是我們常說的任務隊列(task queue)。
JavaScript執行順序可以簡要總結如下:
開始 -> 取task queue第一個task執行 -> 取microtask全部任務依次執行 -> 取task queue下一個任務執行 -> 再次取出microtask全部任務執行 -> ...
循環往復,直至兩個隊列全部任務執行完畢。
參考資料
Tasks, microtasks, queues and schedules
github-setImmediate.js
Promises/A+
知乎-Promise的隊列與setTimeout的隊列有何關聯?
stack overflow-Difference between microtask and macrotask within an event loop context
阮一峰-JavaScript 運行機制詳解:再談Event Loop