我有一个 2 分钟的计时器,从单击 btn 开始计时。如果您单击 btn,它会完美运行,完成 2 分钟后再次单击 btn,它会完美运行。
问题:如果用户在完成 2 分钟之前单击 btn,计时器将重新启动并并行启动计时器两次或 n 次。
我需要帮助,每次点击计时器应从头开始并仅运行一个计时器。
请参阅“运行代码片段”以获得更清晰的信息。
$('.timer-btn').off('click').on('click', myfunction);
function myfunction(){
var countdown = 2 * 60 * 1000;
var timerId = setInterval(function(){
countdown -= 1000;
var min = Math.floor(countdown / (60 * 1000));
//var sec = Math.floor(countdown - (min * 60 * 1000)); // wrong
var sec = Math.floor((countdown - (min * 60 * 1000)) / 1000); //correct
if (countdown <= 0) {
alert("30 min!");
clearInterval(timerId);
//doSomething();
} else {
$("#timerDiv").html(min + " : " + sec);
}
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="timerDiv"> timer here </div>
<div class="timer-btn"> Click Me </div>
最佳答案
您需要先清除上一个间隔,然后才能开始新的间隔。
var timerId;
function myfunction(){
var countdown = 2 * 60 * 1000;
timerId = clearInterval(timerId);
timerId = setInterval(function(){
countdown -= 1000;
var min = Math.floor(countdown / (60 * 1000));
//var sec = Math.floor(countdown - (min * 60 * 1000)); // wrong
var sec = Math.floor((countdown - (min * 60 * 1000)) / 1000); //correct
if (countdown <= 0) {
alert("30 min!");
clearInterval(timerId);
//doSomething();
} else {
$("#timerDiv").html(min + " : " + sec);
}
}, 1000);
}
$('.timer-btn').off('click').on('click', myfunction);
关于javascript - 需要帮助(javascript/jquery 计时器功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43184670/