gpt4 book ai didi

javascript - 是否可以终止正在运行的网络 worker ?

转载 作者:搜寻专家 更新时间:2023-11-01 05:01:03 26 4
gpt4 key购买 nike

我有一个网络 worker 使用 ajax 请求运行一项耗时的例行任务。我可以在不等待它们完成的情况下从主线程终止它们吗?

这就是我生成和终止它的方式:

$("button.parse-categories").click(function() {
if (parseCategoriesActive==false) {
parseCategoriesActive = true;
parseCategoriesWorker = new Worker("parseCategories.js");


$("button.parse-categories-cancel").click(function() {
parseCategoriesWorker.terminate();
parseCategoriesActive = false;
});
}
});

这是 worker 代码:

function myAjax(url, async, callback) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
callback(xmlhttp.responseText);
if (xmlhttp.readyState==4 && xmlhttp.status!=200) {
self.postMessage("error");
throw "error in ajax: "+xmlhttp.status;
}
}
xmlhttp.open("GET", url, async);
xmlhttp.send();
}

var parseCategoriesActive = true;
var counter = 0;
do {
myAjax('parser.php', false, function(resp) {
if (resp=='success')
parseCategoriesActive = false;
else {
counter += Number(resp);
self.postMessage(counter);
}
});
} while (parseCategoriesActive==true);

最佳答案

你可以使用 terminate() 杀死任何网络 worker .

引自 MDN :

The Worker.terminate() method immediately terminates the Worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once.

关于javascript - 是否可以终止正在运行的网络 worker ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21625419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com