我正在使用web workers在网页中添加自定义数量的倒计时计时器。每个计时器创建计时器web worker的一个实例。一切正常。。。但我想在计时器等于“00:00”时终止web worker。当计时器过期时,以下代码将始终终止页面中显示的最后一个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 ...");
}
}