postMessage如何用作nextTick或setTimeout(__,0)的替代?

时间:2015-01-05 21:26:31

标签: javascript

我听说postMessage是谷歌Chrome实现的nextTick。我对此声明感到有些困惑,因为我认为postMessage用于在网络工作者之间进行通信。

我尝试过类似postMessage(function() {return;});的表达式,并且只有在事件循环空闲时才会调度函数而不是调度函数。似乎postMessage只按预期接收消息。

当事件循环空闲时,如何使用postMessage作为调度函数调用的方法?

1 个答案:

答案 0 :(得分:5)

Google Chrome实际上是在V8上运行的,它具有微任务队列的概念。 postMessage部分是DOM API的一部分,它调度微任务 - 类似于nextTick在节点中的作用(尽管铬循环周期与Node的非常不同)。

有一个老hack使用postMessage来模拟看起来像这样的setTimeout(fn, 0)

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", "*");
}

使用MessageChannel而不是直接使用窗口有巧妙的技巧,但它们都是一样的想法。

你可以找到这种技术的旧提及in this blog post它很少被使用,因为使用变异观察者可以更快地破解更快的setTimeout。

以下是关于不同技术的a relatively modern source

相关问题