无法在 js 中对秒表使用清除间隔方法

Failing to use clear interval method for a stopwatch in js

我正在尝试为 运行 游戏创建一个秒表(在点击第一张卡片时开始,在打开所有卡片时停止)并且与 setInterval 不同,它应该正常工作,我无法得到clearInterval 开始工作。

var elPrevCard = null;
var flippedCards = 0;
let elNewGameBtn = document.querySelector('.new-game');
let elAllCards = document.querySelectorAll('.card');
var TOTAL_COUPLES_COUNT = 3;

let elStopwatch = document.querySelector('.stopwatch');
let ms = 0;
let sec = 0;
let min = 0;
let time;

function stopwatchTime() {
    ms++;
    if (ms >= 100) {
        sec++;
        ms = 0;
    }
    
    if (sec === 60) {
        min++;
        sec = 0;
    }
    
    if (min === 60) {
        ms, sec, min = 0;
    }
    
    let millis = ms < 10 ? `0` + ms : ms;
    let seconds = sec < 10 ? `0` + sec : sec;
    let minute = min < 10 ? `0` + min : min;
    
    let timer = `${minute}:${seconds}:${millis}`;
    elStopwatch.innerHTML = timer;
};

function startStopwatch() {
    time = setInterval(stopwatchTime, 10);
}

function stopStopwatch() {
    clearInterval(time);
}

function resetStopwatch() {
    ms = 0;
    sec = 0;
    min = 0;
    
    elStopwatch.innerHTML = `00:00:00`;
}


for (let i = 0; i < elAllCards.length; i++) {
    elAllCards[i].addEventListener('click', startStopwatch();
    });
}

function cardClick(elCard) {
    elCard.classList.add('flipped');
    
    if (elPrevCard === null) {
        elPrevCard = elCard;
    } else {
        var card1 = elPrevCard.getAttribute('data-card');
        var card2 = elCard.getAttribute('data-card');
        
        if (card1 !== card2) {
            setTimeout(function() {
                elCard.classList.remove('flipped');
                elPrevCard.classList.remove('flipped');
                elPrevCard = null;
            }, 1000);
            
        } else {
            flippedCards++;
            elPrevCard = null;
            
            if (TOTAL_COUPLES_COUNT === flippedCards) {
                stopStopwatch();

                elNewGameBtn.style.display = 'inline';
            }
        }
    }
}

elNewGameBtn.addEventListener('click', function newGame() {
    for (let i = 0; i < elAllCards.length; i++) {
        elAllCards[i].classList.remove('flipped');
    }
    
    flippedCards = 0;
    elNewGameBtn.style.display = 'none';
    resetStopwatch();
});

非常感谢对此的帮助,我不知道我在这里遗漏了什么。

在此先感谢所有帮助者!

你可以简单的查看一下time当前是否持有一个值,在清除区间的时候设置为null

注意:另外,在添加监听器时,一定要传递函数而不是调用它。所以 card.addEventListener('click', startStopwatch); 不是 card.addEventListener('click', startStopwatch());

let time = null;

// ...

function startStopwatch() {
  if (time === null) {
    time = setInterval(stopwatchTime, 10);
  }
}

function stopStopwatch() {
  if (time !== null) {
    clearInterval(time);
    time = null;
  }
}

//...

for (const card of elAllCards) {
  card.addEventListener('click', startStopwatch);
}