Web Workers | Interview Questions

--

Topic Covered:

What is a Web Worker?
What problem do Web Workers solve?
How do you create a Web Worker?
What is the communication mechanism between a Web Worker and the main thread?
What types of data can be transferred between a Web Worker and the main thread?
What are the limitations of Web Workers?
How do you terminate a Web Worker?
What are some common use cases for Web Workers?
What are the different types of Web Workers?
How do you handle errors in Web Workers?

Web Workers:

A web worker is a piece of browser functionality. It is the real OS threads that can be spawned in the background of your current page so that it can perform complex and resource-intensive tasks.

Imagine that you have some large data to fetch from the server, or some complex rendering needs to be done on the UI. If you do this directly on your webpage then the page might get jankier and will impact the UI.

To mitigate this, you can simply create a thread — that is a web worker — and let the web worker take care of the complex stuff.

You can communicate with the web worker in a pretty simple manner which can be used to transfer data to and fro from the worker to the UI.

Following are some key features of the Web Workers:

  • Web-workers are threaded JavaScript.
  • Web-workers requires more space and CPU time.
  • Web-workers enhances the speed of a website.
  • Web-worker executes codes on the client side (not server-side).
  • Web worker threads communicate with each other using postMessage() callback method

Common examples of web workers would be:

  • Dashboard pages that display real-time data such as stock prices, real-time active users, and so on
  • Fetching huge files from the server
  • Autosave functionality

Syntax for Creating a Web Worker

It is used to create a web worker
worker = new Worker("webWorker.js");

Syntax for Terminating a Web Worker

It is used to terminate a web worker.
worker.terminate();

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Worker Example</title>
</head>
<body>
<h1>Web Worker Example</h1>
<button onclick="startWorker()">Start Worker</button>
<p id="result"></p>

<script>
function startWorker() {
const worker = new Worker('worker.js');

worker.onmessage = function(event) {
document.getElementById('result').textContent = event.data;
};
}
</script>
</body>
</html>
function doHeavyTask() {
// Simulate a heavy CPU task
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += i;
}
return result;
}

// Listen for messages from the main thread
onmessage = function(event) {
const heavyResult = doHeavyTask();
postMessage(heavyResult); // Send the result back to the main thread
};

React Example, WebWorker Websocket Example


const Homepage = () => {
const [worker, setWorker] = useState(null);
const [res, setRes] = useState([]);
const [log, setLog] = useState([]);
const [buttonState, setButtonState] = useState(false);

const hanldeStartConnection = () => {
// Send the message to the worker [postMessage]
worker.postMessage({
connectionStatus: "init",
});
};

const handleStopConnection = () => {
worker.postMessage({
connectionStatus: "stop",
});
};

//UseEffect1
useEffect(() => {
const myWorker = new Worker(
new URL("../workers/main.worker.js", import.meta.url)
); //NEW SYNTAX
setWorker(myWorker);

return () => {
myWorker.terminate();
};
}, []);

//UseEffect2
useEffect(() => {
if (worker) {
worker.onmessage = function (e) {
if (typeof e.data === "string") {
if(e.data.includes("[")){
setLog((preLogs) => [...preLogs, e.data]);
} else {
setRes((prevRes) => [...prevRes, { stockPrice: e.data }]);
}
}

if (typeof e.data === "object") {
setButtonState(e.data.disableStartButton);
}
};
}
}, [worker]);

return (
<>
<div className="stats">
<div className="control-panel">
<h3>WebWorker Websocket example</h3>
<button
id="start-connection"
onClick={hanldeStartConnection}
disabled={!worker || buttonState}
>
Start Connection
</button>
&nbsp;
<button
id="stop-connection"
onClick={handleStopConnection}
disabled={!buttonState}
>
Stop Connection
</button>
</div>
<LineChartComponent data={res} />
</div>
<Logger logs={log}/>
</>
);
};

Types of Web Workers

Web Workers provide a way to run scripts in the background, separate from the main thread of your web page. They allow you to perform tasks without interfering with the user interface. Here are the two main types of Web Workers:

1. Dedicated Workers:

  • A dedicated worker is accessible only by the script that spawned it.
  • It runs in its own thread, isolated from the main thread.
  • Useful for scenarios where you want to offload heavy computations or time-consuming tasks without affecting the responsiveness of your web page.
  • Dedicated workers are typically used within a single script.

2. Shared Workers:

  • A shared worker can be accessed by multiple scripts running in different windows, iframes, or other contexts, as long as they are in the same domain.
  • Shared workers are designed for scenarios where you need to share data or coordinate actions across different parts of your application.
  • They provide a way to communicate and collaborate between different tabs or frames.
  • Shared workers are more versatile and can be utilized by various scripts simultaneously.

Interview Questions:

What is a Web Worker?

  • A Web Worker is a JavaScript feature that allows you to run scripts in background threads separate from the main execution thread of a web application.

What problem do Web Workers solve?

  • Web Workers help in offloading tasks from the main thread to improve the responsiveness of web applications. They enable concurrent execution without blocking the UI.

How do you create a Web Worker?

  • You create a Web Worker by instantiating a Worker object in your main JavaScript code, providing the URL of the worker script as an argument.

What is the communication mechanism between a Web Worker and the main thread?

  • Web Workers communicate with the main thread using the postMessage() method and listening for messages via the onmessage event handler.

What types of data can be transferred between a Web Worker and the main thread?

  • Data that can be transferred includes JSON objects, ArrayBuffer, ArrayBufferView, File/Blob objects, and other structured cloneable objects.

What are the limitations of Web Workers?

  • Web Workers cannot directly access the DOM, certain APIs like window and document, and perform synchronous XHR requests. They also have restrictions on accessing resources from different origins due to the same-origin policy.

How do you terminate a Web Worker?

  • You can terminate a Web Worker by calling the terminate() method on the Worker object from the main thread.

What are the different types of Web Workers?

  • There are two types of Web Workers: Dedicated Workers and Shared Workers. Dedicated Workers are dedicated to a single script, while Shared Workers can be shared among multiple scripts.

What are some common use cases for Web Workers?

  • Web Workers are commonly used for CPU-intensive tasks like image manipulation, audio/video processing, data parsing, and encryption/decryption. They can also be used for background tasks like fetching data from a server or processing data received via WebSocket.

How do you handle errors in Web Workers?

  • Errors that occur within a Web Worker can be captured using the onerror event handler. Additionally, you can handle errors by sending messages back to the main thread using postMessage() and then handling them in the main thread.

--

--