HTML5工作人员可以通过调用 close()方法来关闭自己。
有没有办法判断工作进程是处于活动/正在运行还是已关闭?
var myWorker = new Worker("worker.js");
...
if( myWorker.isAlive() ) {
// do stuff
}
答案 0 :(得分:0)
工人本身不会告诉你,但你有两个选择:
isRunning
:示例:
function myScript()
{
isRunning = true;
...do stuff...
isRunning = false;
}
然后在setIntervale
或setTimeout
(重复调用self)中运行一个检查该值的函数。
您还需要处理错误try...catch
,以便在错误结束代码时将其设置为false
。
postMessage
并向您的脚本发送一个请求,告诉您它是否仍在运行。示例:
//Make sure we have a listener
myWorker.addEventListener( 'message', checkIsRunning );
//Now ask
myWorker.postMessage( { request: MyWorker.IS_RUNNING } );
//The worker would have something like:
self.onmessage = function (msg) {
switch (msg.data.aTopic) {
case MyWorker.IS_RUNNING:
self.postMessage( { aTopic: isRunning } );
break;
default:
throw 'no aTopic on incoming message to ChromeWorker';
}
}
请注意,使用两个选项,都不会告诉您Worker对象是否已死(不是),因为始终仍然能够响应消息,直到您致电terminate();
如果您想要在调用close()
函数时捕获,请在工作人员首次运行时将其保存:
myWorker._selfClose = self.close;
然后在你被覆盖的关闭函数中调用它:
close: function()
{
//Mark it as no longer running
this.isRunning = false;
//Call original close function
this._selfClose();
}