Connecting the Dots with Web Workers Example

Thursday, February 18, 2010

Open your console and then enter two numbers in the form below to sum via the Web Worker.

Sum Two Numbers

Example Code

The code that initializes the worker.

(function() {
    // make sure we support workers... if not, exit
    if (!('Worker' in window)) {
        alert('Sorry, your browser does not support Web Workers. Try Firefox 3.5+, Safari 4, or Chrome.');
        return;
    }

    // avaialble actions to run from the worker
    var actions = {
        sum: function(result) {
            console.log('The result was ' + result);
        },
        log: function(message) {
            console.log(message);
        }
    };

    // create the worker
    var myWorker = new Worker('myworker.js');

    // handle a response from the worker
    myWorker.onmessage = function(event) {
        var data        = JSON.parse(event.data), // parse the data
            action      = data.action,            // get the action
            returnValue = data.returnValue;       // get the returnValue

        // if we understand the action
        if (action in actions) {
            // handle the returnValue for the action
            actions[action].call(this, returnValue);
        } else {
            // throw an error? our worker isn't communicating properly
        }
    };

    // expose myWorker to global so we can use it in the demo
    window.myWorker = myWorker;
})();

The code from the worker.

// available actions to run within the worker
var actions = {
    sum: function(a, b) {
        log('Summing: ' + a + ' + ' + b);
        return a + b;
    }
    // other actions
};

// handle a new request from the host
onmessage = function(event) {
    var data   = JSON.parse(event.data), // parse the data
        action = data.action,            // get the requested action
        args   = data.args,              // get the arguments for the action
        result = { action: action };     // prepare the result

    // if we understand the action
    if (action in actions) {
        // execute the action and set the returnValue
        result.returnValue = actions[action].apply(this, args);
    } else {
        // otherwise set the returnValue to undefined
        result.returnValue = undefined;
    }

    // send back the results as a JSON string
    postMessage(JSON.stringify(result));
};

// helper method to log messages
function log(msg) {
    // send a log actions back with the message to log
    postMessage(JSON.stringify({
        action: 'log',
        returnValue: msg
    }));
}

The code to hook up the form and send the message to the worker.

jQuery(function($) {
    // hook up the form
    $('#workerExample').bind('submit', function(event) {
        // get the numbers
        var num1 = parseInt($('#workerExampleNum1').val(), 10) || 0,
            num2 = parseInt($('#workerExampleNum2').val(), 10) || 0;
        // send message to worker
        myWorker.postMessage(JSON.stringify({
            action: 'sum',
            args: [num1, num2]
        }));
        // cancel the default submit behavior
        return false;
    });
});