Q:

JavaScript WebWorker not executing from onClick

I have a web worker specified as such below:
var w;
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("scripts/gameengine.js");
        }
        w.onmessage = function(event) {
            console.log("Testing web worker");
        };
    } else {
        console.log("No support for web workers");
    }
}

 function stopWorker() {
    w.terminate();
    w = undefined;
}

However; when I run startWorker(); from an onClick function I get the error:
Uncaught TypeError: undefined is not a function on line 117

line 117 is w.terminate(); in my stopWorker.
Any ideas?

A:

If the click handler fires twice, w will be undefined on the second invocation.
Defensive programming is advisable, for these reasons:
The code should only call things that are well-defined; otherwise JS tends to block execution of later statements
Properly handled, the console.log can be used to tell you what is happening
function stopWorker() {
    if ( w && (typeof(w.terminate)==='function') ){
       w.terminate();
       w = undefined;
       console.log('terminated worker per click request');
    } else {
       console.log('received click request to terminate worker, but worker undefined');
    }
}

Also, be aware that the last time I checked, workers could not access browser functionality, and could only do message passing back to the main script.  That means no jQuery, no event handling, no trying to write to objects on the screen, etc. Just computing and message passing.

