我在网络工作者中有一些 JavaScript 代码,如下所示。
onmessage = function(event){
setTimeout(function(){
postMessage(event.data + " ,then sent back to the main thread");
}, 4000);
};
每当我运行代码时,设置的超时部分基本上都会跳过而不执行。我的主要 JavaScript 代码每 2 秒调用一次工作程序,设置的时间间隔在我的主要代码部分中可以正常工作。然而这部分代码不起作用。有人知道为什么吗?感谢您的帮助。
你能看到它的输出吗?
onmessage = function(event){
console.log("onmessage event is:",event);
setTimeout(function(){
console.log("timeout from onmessage, event is:",event);
postMessage(event.data + " ,then sent back to the main thread");
}, 4000);
};
除非事件为空,否则我看不到代码有问题,但这会导致错误,您也可以在控制台中看到该错误。
我的猜测是,post 消息是在 setTimeout 的上下文中执行的,通常是 Window,它没有在工作线程中定义,请尝试在 post 消息前面添加 self 以确保它在正确的范围内。
self.onmessage = function(event){
setTimeout(function(){
self.postMessage(event.data + " ,then sent back to the main thread");
}, 4000);
};
这是一个可以正常工作的网络工作者的一般结构。
// I've found this syntax for handling the initial message event
// to be the most reliable
self.addEventListener('message', function(e) {
// Do what you need to do here, i.e:
// for (var p in self) { result += '\n' + p + '=' + self[p]; }
// and then post 'result' as the return message on log it from
// the main thread to discover what objects are exposed by the
// VM inside the worker.
// Then 'return' the result
self.postMessage('this is my response');
});
很抱歉复活一个非常古老的问题 - 但由于这是顶级搜索引擎结果,我想提供另一个答案。
由于 JavaScript 的单线程方法,
setTimeout
仅在当前调用堆栈清空时触发。当 setTimeout
处于无限循环(或运行时间非常长的操作)内时,在该循环/操作结束之前它不会触发。
例如,您可能会阅读以下代码并期望 1 秒后出现
"Surprise!"
。但是,只有在循环结束后(大约五秒后)才会记录该字符串。
setTimeout(function () {
console.log("Surprise!");
}, 1000); // 1 second
const start = new Date().getTime();
while ((new Date().getTime()) - start < 5000) {
// do nothing
}