gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot call method 'terminate' of null (web worker)

转载 作者:行者123 更新时间:2023-11-30 05:38:32 25 4
gpt4 key购买 nike

我正在尝试为我的游戏添加计时器

这是下面的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终止。

最佳答案

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

    var w = null;

初始化为:

    var w;

关于javascript - 未捕获的类型错误 : Cannot call method 'terminate' of null (web worker),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com