Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to terminate a running web worker?

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;
        });             
    }
});

This is the worker code:

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);
like image 578
Gherman Avatar asked Feb 07 '14 10:02

Gherman


People also ask

Can a web worker terminate itself?

Terminating a Worker We can kill a worker's task by using the terminate() function or have it terminate itself by calling the close() function on self.

How do I stop web worker?

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

How can you end a web worker that is running beyond expected time?

Web Workers don't stop by themselves but the page that started them can stop them by calling terminate() method. worker. terminate(); A terminated Web Worker will no longer respond to messages or perform any additional computations.

How do I stop a shared worker?

A shared worker can itself be permanently terminated by calling self. close() inside its JS. You can also send a message from the parent script to kill the worker: // script.


1 Answers

You can kill any webworker using terminate().

Citing from 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.

like image 93
Sirko Avatar answered Nov 02 '22 15:11

Sirko