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
}

or:

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:

postMessage(data);

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:

myWorker.terminate();

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

// worker code
close();

Importing Scripts in web worker

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

importScripts('util.js');

Web Worker full code example

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

And worker.js:

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

Leave a Reply

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