Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将postMessage用作nextTick或setTimeout(\u0)的替代方案?_Javascript - Fatal编程技术网

Javascript 如何将postMessage用作nextTick或setTimeout(\u0)的替代方案?

Javascript 如何将postMessage用作nextTick或setTimeout(\u0)的替代方案?,javascript,Javascript,我听说postMessage是Google Chrome对nextTick的实现。我对这种说法有点困惑,因为我认为postMessage是用来在网络工作者之间进行交流的 我尝试过像postMessage(function(){return;})这样的表达式,这只会出错,而不会在事件循环空闲时安排要运行的函数。postMessage似乎只按预期接收消息 当事件循环处于空闲状态时,如何使用postMessage作为调度函数调用的手段?Google Chrome实际上在V8上运行,V8具有微任务队列的

我听说postMessage是Google Chrome对nextTick的实现。我对这种说法有点困惑,因为我认为postMessage是用来在网络工作者之间进行交流的

我尝试过像
postMessage(function(){return;})这样的表达式,这只会出错,而不会在事件循环空闲时安排要运行的函数。postMessage似乎只按预期接收消息


当事件循环处于空闲状态时,如何使用postMessage作为调度函数调用的手段?

Google Chrome实际上在V8上运行,V8具有微任务队列的概念。
postMessage
部分是domapi的一部分,它调度一个微任务-类似于
nextTick
在节点中所做的(尽管chromium循环与节点的非常不同)

有一个老黑客使用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
而不是直接使用窗口有一些聪明的技巧,但都是相同的想法

你可以找到关于这项技术的老生常谈,它很少再被使用了,因为有一种更快的黑客使用变异观察器来实现更快的设置超时


这里介绍了不同的技术。

有一种老方法,通过向自己发布消息,使用
postMessage
生成更快的
setTimeout(fn,0)
——它以异步方式发送,但没有计时器队列的开销。请注意,它不再使用,通常使用
MutationObserver
hack有打字错误吗?为什么要将
fn
传递给
possmessage