2 回答
TA贡献1887条经验 获得超5个赞
该setInterval函数返回一个标识符。将间隔 ID 存储在变量中。这允许您在需要时使用clearInterval()取消间隔。
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var interval = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(interval);
}
}, 1000);
}
$('.start').on('click', function(){
var oneMinute = 5 * 1, // 5 Seconds for easy testing
display = document.querySelector('#time');
startTimer(oneMinute, display);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="time">
00:00
</div>
<button type="button" class="start">
START
</button>
TA贡献1877条经验 获得超1个赞
您需要存储间隔 ID 并用于clearInterval(intervalId);停止它。
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var intervalId = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(intervalId);
}
}, 1000);
}
$('.start').on('click', function(){
var oneMinute = 60 * 1,
display = document.querySelector('#time');
startTimer(oneMinute, display);
})
添加回答
举报