我有两个函数,一个是通过单击“开始”按钮触发的。
function startGame() {
setInterval(setCellPosition, 3000);
setTimeGame = setTimeout(startGame, 2000);
setTime();
};第二个按钮,在单击重置按钮后调用。
function resetGame() {
scoreBox.innerHTML = "0";
timeBox.innerHTML = "60";
liveBox.innerHTML = "3";
clearTimeout(setTimeGame)
};resetGame函数不能工作。值(分数、时间、活动)被重置,但是startGame函数没有停止。怎么修呢?如何停止startgame函数?
发布于 2019-01-20 15:21:05
虽然你应该重新考虑你的算法,因为你现在拥有的是有点复杂的开始和停止你的游戏。
但是,该解决方案的思想是将所有超时和间隔对象存储在一个数组中。当重置发生时,您循环遍历每个对象并停止它。
然后你重新设置数组。
const sts = []; //all set timeouts and intervals
function startGame() {
sts.push(setInterval(setCellPosition, 3000));
sts.push(setTimeout(startGame, 2000));
setTime();
};
function resetGame() {
scoreBox.innerHTML = "0";
timeBox.innerHTML = "60";
liveBox.innerHTML = "3";
sts.forEach(clearTimeout);
sts.length = 0;
};根据MDN:
返回的timeoutID是一个正整数值,它标识调用setTimeout()创建的计时器;该值可以传递给clearTimeout()以取消超时。 了解setTimeout()和setInterval()共享相同的ID池可能很有帮助,而且clearTimeout()和clearInterval()在技术上可以互换使用。但是,为了清晰起见,您应该始终尝试匹配它们,以避免在维护代码时出现混淆。
发布于 2019-01-20 15:25:04
如果将setInterval替换为gameOver标志和包含setTimeout的while循环,如下所示:
let gameOver = false;
function startGame() {
while(gameOver == false){
setTimeout(setCellPosition, 3000);
}
// Note: It seems strange that you're recursively calling `startGame` here
setTimeGame = setTimeout(startGame, 2000);
setTime();
};...Then在您的resetGame函数中,您可以设置gameOver = true来停止循环;
https://stackoverflow.com/questions/54277835
复制相似问题