Web worker - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

A web worker is a JavaScript script executed from an HTML page that runs in the background, independently of user-interface scripts that may also have been executed from the same HTML page.

The simplest use of web workers is for performing a computationally expensive task without interrupting the user interface.

Web workers interact with the main document via message passing. The following code creates a Worker that will execute the JavaScript in the given file.

var worker = new Worker("worker_script.js");

To send a message to the worker, the postMessage method of the worker object is used as shown below.

worker.postMessage("Hello World!");

The onmessage property uses an event handler to retrieve information from a worker.

worker.onmessage = function(event) {
	alert("Received message " + event.data);
	doSomething();
}
	
function doSomething() {
	//do work
	worker.postMessage("Work done!");
}

worker.terminate();

Once a worker is terminated, it goes out of scope and the variable referencing it becomes undefined; at this point a new worker has to be created if needed.