Search code examples
javascriptmultithreadingweb-worker

Does self.close actually kill the web worker thread?


See this example:

// CLOSEWORKER.JS:

self.postMessage('foo');
self.close();
self.postMessage('bar');
setTimeout(() => self.postMessage('baz'), 0);

// MAIN.JS:

const worker = new Worker('./worker.js');
worker.onmessage = ({data}) => console.log(data);

Even if I have invoked self.close(),the next line self.postMessage('bar'); still executed and log 'bar'.I can't understand that since the close method should just kill the worker thread right after being called.

Also ,see another example:

TERMINATEWORKER.JS:

self.onmessage = ({data}) => console.log(data);

MAIN.JS:

const worker = new Worker('./worker.js');
setTimeout(() => {
 worker.postMessage('foo');
 worker.terminate();
 worker.postMessage('bar');
 setTimeout(() => worker.postMessage('baz'), 0);
}, 1000)

When using the terminate method instead of the close method, the code executed as I expected. It just logs 'foo', no-log any other thing, which suggests that the thread has been killed right after calling the terminate method.


Solution

  • WorkerGlobalScope.close() when called discards any tasks that have been scheduled and sets the closing flag of the WorkerGlobalScope, effectively preventing any new task to get queued.

    However, it doesn't stop the execution of the current task.

    So indeed, in your first example, it will run the current script until its end and still execute the self.postMessage('bar') operation, that your main thread will be able to handle.

    Worker.terminate() on the other hand will also "[a]bort the script currently running in the worker."