Thursday, January 28, 2021

What is Web Worker

Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null) or fetch (with no such restrictions). Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa). This article provides a detailed introduction to using web workers.


A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error.


You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB.


Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data attribute.) The data is copied rather than shared.


Dedicated Workers 


As mentioned above, a dedicated worker is only accessible by the script that called it. 


Spawning a Dedicated worker 


Creating a new worker is simple. All you need to do is call the Worker() constructor, specifying the URI of a script to execute in the worker thread (main.js):


var myWorker = new Worker('worker.js');


The magic of workers happens via the postMessage() method and the onmessage event handler. When you want to send a message to the worker, you post messages to it like this (main.js):


first.onchange = function() {

  myWorker.postMessage([first.value,second.value]);

  console.log('Message posted to worker');

}


second.onchange = function() {

  myWorker.postMessage([first.value,second.value]);

  console.log('Message posted to worker');

}



So here we have two <input> elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.

In the worker, we can respond when the message is received by writing an event handler block like this (worker.js):



onmessage = function(e) {

  console.log('Message received from main script');

  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);

  console.log('Posting message back to main script');

  postMessage(workerResult);

}


The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:



myWorker.onmessage = function(e) {

  result.textContent = e.data;

  console.log('Message received from worker');

}


Terminating Worker 


If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's terminate method:


myWorker.terminate();




References:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

No comments:

Post a Comment