我能够从正在从事的某些课堂工作中获得以下代码。它可以很好地满足我的需求,我喜欢我可以致电startTime();
来启动它。但是,我现在需要确定如何停止它。有没有办法做startTime(stop);
或类似的事情?
function startTime() {
let hours = 0;
let minutes = 0;
let seconds = 0;
const timer = setInterval(function () {
seconds++;
if (seconds === 60) {
minutes++;
seconds = 0;
}
second.innerHTML = formatTime();
}, 1000);
function formatTime() {
let sec = seconds > 9 ? String(seconds) : '0' + String(seconds);
let min = seconds > 9 ? String(minutes) : '0' + String(minutes);
return min + ':' + sec;
}
}
答案 0 :(得分:4)
您需要确定将setInterval
分配给startTime
的 outside 的变量的范围,以便可以访问它并调用clearInterval
在外部。例如,此代码段将为timer
分配一个间隔,然后在5秒后清除该间隔:
let timer;
function startTime() {
let hours = 0;
let minutes = 0;
let seconds = 0;
timer = setInterval(function () {
seconds++;
if (seconds === 60) {
minutes++;
seconds = 0;
}
second.innerHTML = formatTime();
}, 1000);
function formatTime() {
let sec = seconds > 9 ? String(seconds) : '0' + String(seconds);
let min = seconds > 9 ? String(minutes) : '0' + String(minutes);
return min + ':' + sec;
}
}
function stopTime() {
clearInterval(timer);
}
startTime();
setTimeout(stopTime, 5000);
<div id="second"></div>
答案 1 :(得分:1)
我个人更喜欢使用一个类来跟踪setInterval
的返回值。
class Timer {
constructor(callback) {
this.minutes = 0
this.seconds = 0
this.timer = null
this.callback = callback
}
start() {
// Make sure the timer isn't already running!
if (this.timer !== null) {
return
}
// Execute the callback every second, passing in
// the new number of minutes and seconds
this.timer = setInterval(() => {
this.seconds++
if (this.seconds === 60) {
this.minutes++
this.seconds = 0
}
this.callback(this.minutes, this.seconds)
}, 1000)
}
stop() {
clearInterval(timer)
this.timer = null
}
}
const timer = new Timer((minutes, seconds)) => {
const sec = seconds > 9 ? String(seconds) : '0' + String(seconds)
const min = seconds > 9 ? String(minutes) : '0' + String(minutes)
const formatted = min + ':' + sec
second.innerHTML = formatted
})
timer.start() // start the timer
timer.stop() // stop the timer
答案 2 :(得分:1)
我只是将计时器从函数返回给调用者。然后,呼叫者可以根据需要使用它:
function startTime() {
let hours = 0;
let minutes = 0;
let seconds = 0;
function formatTime() {
let sec = seconds > 9 ? String(seconds) : '0' + String(seconds);
let min = seconds > 9 ? String(minutes) : '0' + String(minutes);
return min + ':' + sec;
}
// return this value to the caller so they can stop it
return setInterval(function () {
seconds++;
if (seconds === 60) {
minutes++;
seconds = 0;
}
console.log(formatTime());
}, 1000);
}
// receives the result of setTimout
let timerControl = startTime()
// stop it after a few seconds
setTimeout(()=> {
clearTimeout(timerControl)
console.log("Stopped")
}, 4000)