Ghe*_*man 4 javascript web-worker
我有一个Web工作者使用ajax-requests运行耗时的例程任务.我可以从主线程中终止它们而不是等待它们完成吗?
这就是我产生和终止它的方式:
$("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;
});
}
});
Run Code Online (Sandbox Code Playgroud)
这是工人代码:
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);
Run Code Online (Sandbox Code Playgroud)
你可以使用杀死任何webworker terminate()
.
引用MDN:
Worker.terminate()方法立即终止Worker.这并不能为工人提供完成业务的机会; 它只是立即停止.
归档时间: |
|
查看次数: |
5274 次 |
最近记录: |