admin管理员组文章数量:1332395
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();
}
}
I'm getting Uncaught RangeError: Maximum call stack size exceeded and something tells me it's because of the code above.
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();
}
}
I'm getting Uncaught RangeError: Maximum call stack size exceeded and something tells me it's because of the code above.
Share Improve this question asked Feb 26, 2014 at 13:38 Misha SlyusarevMisha Slyusarev 1,3833 gold badges19 silver badges48 bronze badges 5-
Why not use
setInterval()
instead if you want it to repeat? – Lloyd Commented Feb 26, 2014 at 13:40 - I'd like to stop it when the database stop being busy. – Misha Slyusarev Commented Feb 26, 2014 at 13:41
-
1
@MishaSlyusarev Then use
clearInterval()
after your condition is met. – Sirko Commented Feb 26, 2014 at 13:43 - 1 Are you sure the problem is the timeout for the stack size? Are you using any recursion in the webworker code? – MarcoL Commented Feb 26, 2014 at 13:46
- Not sure that's the case, just wanted to figure out the proper way of using setTimeout from web workers. – Misha Slyusarev Commented Feb 26, 2014 at 13:51
1 Answer
Reset to default 4If 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.
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);
}
- 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.
本文标签: javascriptsetTimeout from a web workerStack Overflow
版权声明:本文标题:javascript - setTimeout from a web worker - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742283211a2446476.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论