如果已设置,如何使用 btn 清除间隔
How to clear interval with a btn if it's already set
所以我目前对 JavaScript 和它的概念还很陌生,我正在尝试制作一个游戏,其中有 4 个 btns 启动计时器,然后重置它并在它们中的任何一个出现时再次启动它第二次按下,但每当我按下任何按钮两次时,它就会将计时器加速 2 倍,而不是重置并重新启动它
这是我的代码,
很抱歉,如果它很乱 and/or 难以理解
let time = 5
const countDown = document.querySelector('#countdown')
let challenge = document.getElementById('text')
const btns = document.querySelectorAll('.btn')
let text = ''
function randomText(){
return Math.floor(Math.random() * arr.length)
}
btns.forEach(function(btn){
btn.addEventListener('click', function(e){
time = 5
const timer = setInterval(countdown, 1000)
text = arr[randomText()]
challenge.textContent = text
})
})
function countdown(){
if( time === 0 ){
time = 5
}
time--
countDown.innerHTML = `00:0${time}`
}
let timer;
btns.forEach(function(btn){
btn.addEventListener('click', function(e){
time = 5
clearInterval(timer);
timer = setInterval(countdown, 1000)
text = arr[randomText()]
challenge.textContent = text
})
})
所以我目前对 JavaScript 和它的概念还很陌生,我正在尝试制作一个游戏,其中有 4 个 btns 启动计时器,然后重置它并在它们中的任何一个出现时再次启动它第二次按下,但每当我按下任何按钮两次时,它就会将计时器加速 2 倍,而不是重置并重新启动它
这是我的代码, 很抱歉,如果它很乱 and/or 难以理解
let time = 5
const countDown = document.querySelector('#countdown')
let challenge = document.getElementById('text')
const btns = document.querySelectorAll('.btn')
let text = ''
function randomText(){
return Math.floor(Math.random() * arr.length)
}
btns.forEach(function(btn){
btn.addEventListener('click', function(e){
time = 5
const timer = setInterval(countdown, 1000)
text = arr[randomText()]
challenge.textContent = text
})
})
function countdown(){
if( time === 0 ){
time = 5
}
time--
countDown.innerHTML = `00:0${time}`
}
let timer;
btns.forEach(function(btn){
btn.addEventListener('click', function(e){
time = 5
clearInterval(timer);
timer = setInterval(countdown, 1000)
text = arr[randomText()]
challenge.textContent = text
})
})