Nevin
Nevin

Reputation: 3298

Uncaught TypeError: Cannot call method 'terminate' of null (web worker)

Am trying to add a timer to my game.

This is the web worker below:

startTimer();
    var w = null;
    function startTimer()
    {
        // First check whether Web Workers are supported
        if (typeof (Worker) !== "undefined") {
            // Check whether Web Worker has been created. If not, create a new Web Worker based on the Javascript file simple-timer.js
            if (w == null) {
                w = new Worker("../js/Timer.js");
                console.log(w);
            }
            // Update timer div with output from Web Worker
            w.onmessage = function(event) {
                document.getElementById("timer").innerHTML = event.data;
            };
        } else {
            // Web workers are not supported by your browser
            document.getElementById("timer").innerHTML = "Sorry, your browser does not support Web Workers ...";
        }
    }

// function to stop the timer
    function stopTimer()
    {
        w.terminate();
        timerStart = true;
        w = null;
    }
};

This is my Timer.js file :

var i = 0;

function timedCount()
{
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()", 200);
}

timedCount();

This it the error i come up with,when i try to stop the timer. I also addded a console message as you can see in the picture. This it the error i come up with,when i try to stop the timer. I also addded a console message as you can see in the picture.

EDIT: SOLUTION I found out why the problem occured,it was mainly because the function stopTimer() was being called more than 1 time which resulted in the termination of null.

Upvotes: 2

Views: 476

Answers (1)

Adidev
Adidev

Reputation: 343

In the above code ,you have to set w to null initially.

    var w = null;

Initialize it as just:

    var w;

Upvotes: 1

Related Questions