Module gamejs/thread

gamejs.worker makes it more convinient to work with W3C WebWorkers by providing a way to run CommonJs modules inside of them. GameJs also provides the typically gamejs.ready() and event loop to facilitate communication between workers and the main application.

See the examples/workers directory for a running example.

Create a worker with the main module "foo-worker" (see below for how the worker's module looks like):

var fooWorker = new Worker('./foo-worker');
// Send a message to your worker.
// The Message doesn't have to be a string but it
// must be `JSON.stringify()`-able"foobar");

You can also recieve messages from the worker:

// recieve events from the worker
fooWorker.onEvent(function(event) {
    if(event.timestamp > ...)

And this is how the above referenced "foo-worker" module would looke like. As usual, we need a gamejs.ready() to get started and within that we bind an event handler:

var gamejs = require('gamejs');
gamejs.ready(function() {
    gamejs.event.onEvent(function(event) {
         var plaintext = fastCrack(event.password)

Our event worker could do expensive calculations (seperate and not blocking the main game) when recieving an event. Once the result is caculated, it can be sent back to the main application with{
   info: "important message from worker",
   timestamp: 12232435234

The main application would in turn recieve an event posted like this from fooWorker.onEvent, as seen above.

This module is useful for expensive algorithms where the result does not have to available instantiously (e.g., path-finding) or for continous logic which can be calculated seperately from the rendering loop, and which only needs to feed back into the model of the rendering every now and then (e.g. physics) The main draw back of the Worker model is that you can only communicate with them via text messages (typically JSON.stringify()ed messages).



Class Worker

Instance Methods

Worker (moduleId)

The Worker constructor takes only one argument: a module id. This module will be executed inside the newly created Worker. It is effectively the main module of the Worker.

Inside a Worker, you can use require() to import other scripts or GameJs modules.

Note: A Worker does not have access to the browser's document. So a lot of GameJs modules - everything related to drawing to the canvas - do not work in the Worker.

You can use gamejs.time.*, gamejs.utils.*, gamejs.event.* and probably others (as well as any module you write yourself for this purpose, of course).


String moduleId The Worker's main module id. The main module will be executed in the worker

Worker.prototype.onError (fn, scope)



Worker.prototype.onEvent (fn, scope)


scope (data)

Send a message to the worker


Object data Payload object which gets sent to the Worker




true if this GameJs instance is being executed within a WebWorker

post (data)

Send an event back to the main script.


Object data to be sent back to main script