[英]How to stop calling a function JS
我有兩種功能,一種是通過單擊開始按鈕觸發的
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
功能?
雖然您應該重新考慮算法,因為目前擁有的算法對於啟動和停止游戲有點復雜。
但是,此解決方案背后的想法是將所有超時和時間間隔對象存儲在數組中。 發生重置時,您將遍歷每個對象並將其停止。
然后重置陣列。
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()在技術上可以互換使用,可能會有所幫助。 但是,為清楚起見,您應嘗試始終將它們匹配,以免在維護代碼時造成混淆。
如果用gameOver
標志和包含setTimeout
的while
循環替換setInterval,例如:
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();
};
...然后在resetGame
函數中,可以將gameOver = true
設置為停止循環;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.