【发布时间】:2020-07-13 10:22:22
【问题描述】:
我让 WebWorker 进行计算密集型递归计算,持续几秒钟。我想每 500 毫秒将进度消息发布到父线程(主窗口)。
我尝试使用setInterval 来实现这一点。但是由于线程被主计算阻塞,setInterval在那段时间根本没有执行。
网络工作者代码:
// global variable holding some partial information
let temporal = 0;
// time intensive recursive function. Fibonacci is chosen as an example here.
function fibonacci(num) {
// store current num into global variable
temporal = num;
return num <= 1
? 1
: fibonacci(num - 1) + fibonacci(num - 2);
};
self.onmessage = function(e) {
// start calculation
const result = fibonacci(e.data.value);
postMessage({result});
}
setInterval(function() {
// post temporal solution in interval.
// While the thread is blocked by recursive calculation, this is not executed
postMessage({progress: temporal});
}, 500);
主窗口代码
worker.onmessage = (e) => {
if (e.data.progress !== undefined) {
console.log('progress msg received')
} else {
console.log('result msg received')
console.log(e.data)
}
};
console.log('starting calculation');
worker.postMessage({
'value': 42,
});
参见 jsFiddle 示例 - https://jsfiddle.net/m3geaxbo/36/
当然,我可以在fibonacci 函数中添加一些代码来计算经过的时间并从那里发送消息。但我不喜欢它,因为它会用不相关的代码污染函数。
function fibonacci(num) {
// such approach will work, but it is not very nice.
if (passed500ms()) {
postMessage({progress: num})
}
return num <= 1
? 1
: fibonacci(num - 1) + fibonacci(num - 2);
};
有没有首选的方法,如何在不污染执行计算本身的代码的情况下获得密集的 web-worker 计算的进度?
【问题讨论】:
标签: javascript web-worker