如何使用同一脚本的多个实例终止正确的网络工作者
How to terminate the right web worker with multiple instances of the same script
我正在使用网络工作者在网页中添加自定义数量的倒数计时器。每个计时器都会创建一个计时器 web worker 的实例。一切正常......但我想在计时器等于“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()
。
我正在使用网络工作者在网页中添加自定义数量的倒数计时器。每个计时器都会创建一个计时器 web worker 的实例。一切正常......但我想在计时器等于“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()
。