ThreadJS: Simple convinience wrapper for web workers

Web workers are a new HTML5 API enabling web developers to separate time consuming tasks in a separate thread so the UI thread is not blocked. Eventually every web worker results spawning a new real os-level thread.

However the API requires you to create a separate javascript file which contains the code you want to execute. This may be a burden sometimes as you need to refer to an external file to see what a specific worker is doing.

So i created a simple wrapper on top of web workers which allows you create a thread using a custom function, and (optional) arguments.

The usage is simple as that:

var thread = new Thread(function (customArgs) {
    //Code here will be executed in a web worker.
    //You can use postMessage to send data back to main thread, just like plain web workers.
});

//Optionally handle onmessage & onerror to receive data and error from thread.

thread.onmessage = function(e) {
    console.log('Received message: ' + e.data);
}

thread.onerror = function(e) {
    console.log('Error: ' + e.message);
}

var custom_args = { test: [1,2,3] };

//Start thread passing optional custom parameters
thread.start(custom_args);

//You can stop the thread at any time using the stop method
thread.stop()

You can find the library & an example in github

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s