简体   繁体   中英

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.

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.

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

    var w = null;

Initialize it as just:

    var w;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM