Introduction

Ever find yourself needing to do some number crunching, or create an off time rendering hook or perhaps just needing to create a separate thread for some other purpose, this is how you do it.  

Getting Started

First things first, we need to create a separate javascript file which will house our thread execution code.  In this example, let’s create a file called thread.js and add the following:

function Thread(){
    var _ref = this;
    var _running = null;

    _ref.start = function(){

        //execution code
        function execute(){
            self.postMessage({
                cmd: "console.log",
                value: "Execute called..."
            });
        }

        _running = setInterval(execute, 1000);
    }

    _ref.stop = function(){
        clearInterval(_running);
    }
}

var thread = new Thread();

self.onmessage = function(e){
    thread[e.data.cmd](e.data.args);
}

Understanding Threads

So here’s what happening in this file.  We’ve created a class called Thread and created public methods start() and stop().  Just for an example of functionality we’ve added an execute method loop which is invoked by a setInterval() call every second (1000ms).  The _running variable is assigned the interval handle and cleared when the stop() method is called.  Within the execute() method the postMessage method is called which sends the message over the wall to our main execution script which we will detail below.  Lastly, we create an instance of the Thread class and create an onmessage() handler to deal with incoming messages sent to our Thread class from over the wall in our main execution script.  Here, the Thread instance variable is invoked with the cmd parameter as the method and the args parameter as the arguments passed to the invoked method.  So here’s the main execution script that we will use to create an instance of the thread:

//create a worker thread
var worker = new Worker("thread.js");

//handle messages sent from Thread
worker.onmessage = function(e){
    switch(e.data.cmd){
        case "console.log":
            console.log(e.data.value);
            break;
    }
}

//start the Thread
worker.postMessage({cmd: "start"});

//stop the Thread after 5 seconds
setInterval(function(){
    worker.postMessage({cmd: "stop"});
}, 5000);

Understanding Workers

So let’s walk through the main script.  We create a instance of the Worker class and pass in the script we are going to use as our worker thread, in this case thread.js.  Next we setup an onmessage() handler to receive messages sent from within our Thread.  Next we send a message with the cmd parameter set to start which over the wall evaluates to thread.start().  Lastly, we setup an interval callback to be invoked after 5 seconds (5000ms) to stop the Thread.  Pie, right?  So now what if we want to add a method to the Thread class that takes in parameters and sends a value back to our main script…let’s do it:

function Thread(){

    //existing code omitted here...

    _ref.foo = function(args){
        self.postMessage({cmd: "console.log", value: args});
    }
}

So now we’ve added the method foo() with arguments args and in turn we post a message back over the wall to the main script returning the args passed in as the value.  Now, let’s add the code to invoke it within our main script:

//existing code omitted here...

worker.postMessage({cmd: "foo", args: "bar"});

All we’ve done here is add another postMessage() call with a cmd parameter of foo and an args parameter of bar which evaluates to thread.foo('bar') on the other side of the wall within our Thread class.

Conclusion

Hopefully this has helped to some degree in understanding how javascript worker threads work. Please let me know if you have any questions and I’ll try to help. Thanks for stopping by.


0 Comments

Leave a Reply

Avatar placeholder

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