Skip to content

Web Worker ​

Noted from this video: https://www.youtube.com/watch?v=JMKLXGwltGc

WebWorkers enable Javascript functions to be run on another thread. This makes it easy to offload long running tasks to the WebWorkers API.

However, WebWorkers cannot access the DOM. As such, it makes it much like a network request and response.

Why? ​

Even with the event loop, suppose a callback or a function takes up a lot of time. This results in the function blocking other tasks or events. To solve this, we can make the function a webworker and then use messages to communicate with the worker.

eg, we want to make answer.js a web worker. answer.js

js
onmessage = ev => {
    if (ev.data === "start") {
        let sum = 0;
        for (let i = 0; i < 5000000000; i++) {
            sum += i;
        }
        postMessage(42);
    }
}

main.js

js
const worker = new Worker("answer.js");

export default function App() {
    const [count, setCount] = createSignal(0);
    const [answer, setAnswer] = createSignal(0);

    function getAnswerToLife() {
        worker.postMessage("start");
        worker.onmessage = ev => setAnswer(ev.data);
    }

    return (
        <>
            <h2>The answer to life is {answer()}</h2>
            <h4>The count is {count()}</h4>
            <button onClick={() => setCount(count() + 1)}>+1</button>
            <button onClick={getAnswerToLife}>Get Answer</button>
        </>
    );
}

See also: JavaScript Event Loop.