[英]How to terminate the right web worker with multiple instances of the same script
我正在使用网络工作者在网页中添加自定义数量的倒数计时器。 每个计时器都会创建一个计时器Web工作实例。 一切正常...但是我想在计时器等于“ 00:00”时终止网络工作者。 当计时器到期时,以下代码将始终终止页面中显示的最后一个Web Worker。 如何终止合适的一个?
$(document).ready(function() {
$('.frequency-item').each(function(i, e) {
children = $(e).children();
observationLengthInMinutesId = children[1].id;
timerId = children[3].id;
startTimer(observationLengthInMinutesId, timerId);
});
});
function startTimer(observationLengthInMinutesId, timerId) {
w = null;
if (typeof(Worker) !== "undefined") {
if (w == null) {
w = new Worker("/js/simple-timer.js");
w.postMessage($('#' + observationLengthInMinutesId).val());
}
w.onmessage = function(event) {
$('#' + timerId).text(event.data);
//the problem is here
if (event.data == '00:00') {
w.terminate();
}
/*
I fixed in the following way but without terminating the workers!
I don't like it
if($( '#' + timerId ).text() != '00:00') {
$( '#' + timerId ).text(event.data);
}
*/
};
} else {
// Web workers are not supported by your browser
$('#' + timerId).text("Sorry, your browser does not support Web Workers ...");
}
}
尝试改为调用this.close()
。
有两种方法可以阻止工人:通过调用worker.terminate()
从主网页或致电self.close()
工人本身的内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.