未捕获的TypeError:无法调用null的方法'terminate'(web worker)

时间:2014-03-04 05:52:28

标签: javascript web-worker

我试图为游戏添加计时器

这是网络工作者

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;
    }
};

这是我的 Timer.js 文件:

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. 这是我想出的错误,当我试图停止计时器。我还添加了一个控制台消息,如图所示。

编辑: 解决方案 我发现了问题发生的原因,主要是因为函数stopTimer()被调用了1次以上,导致了null的终止。

1 个答案:

答案 0 :(得分:1)

在上面的代码中,你必须先将w设置为null。

    var w = null;

将其初始化为:

    var w;