来自网络工作者的 setTimeout [英] setTimeout from a web worker

查看:35
本文介绍了来自网络工作者的 setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在无法继续处理数据的情况下暂停 Web Worker 并稍后再试,该怎么办?我可以在网络工作者中以这种方式做到这一点吗?

What if I want to put a web worker on pause if I cannot proceed processing data, and try a second later? Can I do that in this manner inside a web worker?

var doStuff = function() {
    if( databaseBusy() ) {
        setTimeout(doStuff, 1000);
    } else {
        doStuffIndeed();
    }
}

我收到Uncaught RangeError: Maximum call stack size exceeded 并且有人告诉我这是因为上面的代码.

I'm getting Uncaught RangeError: Maximum call stack size exceeded and something tells me it's because of the code above.

推荐答案

如果暂停"您的意思是worker.postMessage() 的进一步调用将被排入队列并且不被处理由工人",那么不,您不能为此使用 setTimeout().setTimeout() 不是一个busywait,而是一种将工作延迟到稍后预定时间的线程内机制.网络工作者仍会在发布后立即从主队列接收新的 onmessage 事件.

If by "pause" you mean "further calls to worker.postMessage() will get queued up and not processed by the worker", then no, you cannot use setTimeout() for this. setTimeout() is not a busywait, but rather an in-thread mechanism for delaying work until a later scheduled time. The web worker will still receive a new onmessage event from the main queue as soon as it is posted.

然而,您可以做的是手动将它们排队,然后使用 setTimeout 尝试稍后处理它们.例如:

What you can do, however, is queue them up manually and use setTimeout to try to process them later. For example:

worker.js

var workQueue = [];
addEventListener('message',function(evt){
  workQueue.push(evt.data);
  doStuff();
},false);

function doStuff(){
  while (!databaseBusy()) doStuffIndeed(workQueue.shift());
  if (workQueue.length) setTimeout(doStuff,1000);
}

  • 每次收到消息时,worker 都会将其放入队列并调用 tryToProcess.
  • tryToProcess 只要数据库可用,就会一次从队列中提取一条消息.
  • 如果数据库不可用并且还有消息,它会在 1 秒后重试.
    • Each time a message is received the worker puts it into a queue and calls tryToProcess.
    • tryToProcess pulls messages from the queue one at a time as long as the database is available.
    • If the database isn't available and there are messages left, it tries again in 1 second.
    • 这篇关于来自网络工作者的 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆