谷歌瀏覽器實際上運行在V8上,它具有微任務隊列的概念。 postMessage
部分是DOM API的一部分,它調度一個微任務 - 類似於節點中的nextTick
(儘管鉻循環週期與節點的非常不同)。
存在使用postMessage的模擬setTimeout(fn, 0)
,看起來像這樣的老黑客:直接使用MessageChannel
代替窗口手段高明
var queue = [];
window.addEventListener("message", function(e){
if((e.source !== window) || (e.data === "flush")) return; // not the right message
queue.forEach(function(fn){ fn(); }); // call all functions;
queue = []; // clean the queue;
});
function nextTick(fn){
queue.push(fn); // add the function
window.postMessage(fn, "flush", "*");
}
有,但它是完全一樣的想法。
你可以發現這種技術的老陳述in this blog post它很少再使用了,因爲使用突變觀察者可以更快速地使用setTimeout。
這裏是a relatively modern source關於不同的技術。
[引文需要] – Nit
有一種老式的黑客通過向自己發佈消息使用postMessage產生更快的'setTimeout(fn,0)' - 它被異步調度,但沒有定時器隊列的開銷。請注意,它不再使用,而是通常使用「MutationObserver」hack代替。 –
這裏 - 一些閱讀材料:http://dbaron.org/log/20100309-faster-timeouts –