[英]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.