Saturday, August 03, 2024

Web Workers

Web Workers allow you to perform resource-intensive computations in background threads, without blocking the main thread that handles user interactions and UI updates. This makes it possible to perform tasks such as data processing, complex calculations, and large data fetching asynchronously, keeping your web application responsive.

The following example shows the basics of using a web worker to perform a simple "sum" calculation.

1. Create a Web Worker Script

First, create your web worker script:

// worker.js
onmessage = (e) => {
  const workerResult = e.data[0] + e.data[1];
  postMessage(workerResult);
};

As shown above, the web worker performs the computation in the onmessage event handler and then calls postMessage, to post the result back to the main thread.

2. Invoke the Web Worker in Your Main Script

In the main script, initialise the web worker and invoke it with some data:

<html>
  <head/>
  <body>
    <h1>Web Worker Example</h1>
    <p id="result">Computing...</p>
    <script>
      const worker = new Worker('worker.js');
      worker.onmessage = (e) => {
        document.getElementById('result').textContent = `Result: ${e.data}`;
      };
      worker.postMessage([1, 2]);
    </script>
  </body>
</html>

Communication between the main script and the web worker is done using the postMessage method to send messages and the onmessage event to receive messages.

React Example

Here is how you would do it in React:

import React, { useState } from 'react';

const App = () => {
  const [result, setResult] = useState(null);

  const handleClick = () => {
    // Create a new Web Worker
    const worker = new Worker(new URL('./worker.js', import.meta.url));

    // Set up message handler
    worker.onmessage = (e) => {
      setResult(e.data);
      worker.terminate(); // Clean up the worker
    };

    // send data to the worker
    worker.postMessage([1, 2]);
  };

  return (
    <div>
      <h1>Simple Web Worker Example</h1>
      <button onClick={handleClick}>Start Computation</button>
      {result !== null && <p>Result from Worker: {result}</p>}
    </div>
  );
};
export default App;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.