Canva

I interviewed at Canva (see here) a while back. Canva's a great company that I highly recommend. They typically hire the best 2-5% of developers. Fun fact: one of the Co-founders created the maps app that sold to Google and became Google Maps.

During the interview process I was introduced to client-side parallel JavaScript using the Web Worker API. While JavaScript is known for being single-threaded (at least client-side), there are a few ways to get asynchronous as well as multi-threaded functionality out of both the server and client-side.

Here, we take a look at how to set up a single task web worker to enable parallel execution of tasks client-side.

Web Worker Template

Web Worker API Documentation

A web worker is created to handle a specific task specified in a JavaScript file
A web worker executes a JavaScript file

The web worker communicates with your main logic using postMessage() and the message event listener

Here's our starting .html:


<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title>Web Worker API Example</title>
</head>
<body>
    <div id='container'></div>
</body>
</html>

<script src='scripts/web-worker-caller.js'></script>

web-worker-caller.js


'use strict';

if (window.Worker) {
    var worker = new Worker('single-task-web-worker.js');

    worker.postMessage('');

    //Listener for this worker's finished message
    worker.addEventListener('message', function (e) {
        worker.terminate();
    });
}

single-task-web-worker.js

Place the following script in the same directory as web-worker-caller.js


'use strict';

importScripts();

//Worker's listener
addEventListener('message', function (e) {
        /**
         *Logic here
         */

        //Then send message or data back when done
        self.postMessage('');
});

How It Works

web-worker-caller.js creates a worker


var worker = new Worker('single-task-web-worker.js');


using:


worker.postMessage('');


we send a message to the web worker which is received here in single-task-web-worker.js:


addEventListener('message', function (e) {
        /**
         *Logic here
         */

        //Then send message or data back when done
        self.postMessage('');
});

When the worker's complete it will send a message back to the main logic which then terminates the worker in web-worker-caller.js


    worker.addEventListener('message', function (e) {
        worker.terminate();
    });