是否可以终止正在运行的 Web Worker? [英] Is it possible to terminate a running web worker?

查看:31
本文介绍了是否可以终止正在运行的 Web Worker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络工作者正在运行一个带有 ajax 请求的耗时的例行任务.我可以在不等待它们完成的情况下从主线程终止它们吗?

I have a web worker running a time-consuming routine task with ajax-requests. Can I terminate them from a main thread not waiting for them to finish?

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

That's how I spawn and terminate it:

$("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;
        });             
    }
});

这是工作代码:

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().

You can kill any webworker using terminate().

引用自 MDN:

Worker.terminate() 方法立即终止 Worker.这不会为工人提供完成其操作的机会;它只是立即停止.

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.

这篇关于是否可以终止正在运行的 Web Worker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆