Rain and snow effects with Phaser

Web Workers tutorial

Until recently running JavaScript thread was impossible but now with the new standards you have the option to create web workers. The worker thread can perform actions without interfering with the interface so the user can continue what he is doing despite the web worker working at the background.

How do you create Web Worker

Its very simple – it only needs the script to be used as parameter.

var webWorker = new Worker('work.js');

You may need to check if the browser supports web workers:

if(window.Worker) {
    // we have worker, do the other stuff
} else {
    //  worker is not available


if (typeof(Worker) !== "undefined") {
    // yes, create our worker and do the job
    var webWorker = new Worker("worker_script.js");
} else {
    // no support, go to an alternative route

Sending data to worker

Your script can communicate with the worker through messages.

var worker = new Worker('worker_script.js');
worker.postMessage('Hello Worker');

Sending data from the worker

The worker uses the same postMessage to send data to the main interface. In the worker script:


Receiving data

And in your code you can get messages from the worker thread. This is achieved through event listeners.

worker.addEventListener('message', function(e) {
    console.log('Worker send: ', e.data);
}, false);

Terminating a worker

Terminating a worker is easy, you just need to call worker.terminate:


In the thread script, the worker can close itself when done by calling close:

// worker code

Importing Scripts in web worker

To import scripts into web worker you use importScripts() global function:


Web Worker full code example

<!DOCTYPE html>
        <title>Web Worker Example</title>      
        <div id="res"></div>
            var worker = new Worker('worker.js');
            worker.onmessage = function(event) {
                document.getElementById('res').textContent += event.data + " ";

And worker.js:

for(var i = 0; i < 10; i++) {

Leave a Reply

Your email address will not be published. Required fields are marked *