<script>
var minutes = 1;
var seconds = 45;
$(document).ready(function () {
setInterval(startTimer, 1000);
});
function startTimer() {
document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}
}
if (minutes == 0 && seconds == 0) {
document.getElementById('next').click();
minutes = 1;
seconds = 45;
}
}
</script>
这是我的计时器代码,单击ID为#next的按钮后应重新启动。我做了很多事情,但是没用。请帮忙。
按钮ID =下一步
答案 0 :(得分:1)
这是我为您解决的问题。
我注意到
$(document).ready()
,所以我立即认为您是 使用jQuery
。
var timerInterval
是对您启动的计时器的直接引用。
要停止计时器,请使用clearInterval(timerInterval)
[setTimeout()
也是如此。
我已经更改了您的倒数计时器,因为我不厌其烦地修复它。
var timerInterval;
let minutes = 2;
let seconds = 42;
let duration = (minutes * 60) + seconds;
let display = document.querySelector('#timer');
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
timerInterval = 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) {
timer = duration;
clearInterval(timerInterval);
}
}, 1000);
}
startTimer(duration, display);
$('button').click((e) => {
clearInterval(timerInterval);
startTimer(duration, display);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
<br>
<button>Reset Timer</button>
答案 1 :(得分:0)
没有html,我不能一步一步给您,但基本上,您需要清除间隔后才能重新启动。
<script>
var minutes = 1;
var seconds = 45;
var interval_id=setInterval(startTimer, 1000);
$('#next').on("click",function(){
clearInterval(interval_id);
minutes = 1;
seconds = 45;
document.getElementById("timer").innerHTML ="";
interval_id=setInterval(startTimer, 1000);
});
function startTimer() {
document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}
}
if (minutes == 0 && seconds == 0) {
minutes = 1;
seconds = 45;
}
}
</script>
答案 2 :(得分:0)
您不应依赖setInterval(或setTimeout)来计算时间值。它不保证在指定的时间间隔被调用。我相信在某些情况下,浏览器也可能会暂停它。
您可以尝试这样的事情:
<span id='timer'></span>
<button id='next'>Next</button>
<script>
var btn = document.getElementById('next');
btn.addEventListener('click', function(e) {
// 10 is the duration in seconds
startNextTimer(10, function() { alert('done!');} );
});
function startNextTimer(numSecondsDuration, callback) {
var label = document.getElementById('timer');
var endDate = new Date();
endDate.setSeconds(endDate.getSeconds() + numSecondsDuration);
var calcTimeLeft = function() { return Math.ceil((endDate - (new Date())) / 1000); };
label.innerHTML = calcTimeLeft() + " secs";
var intervalId = setInterval(function() {
var numSecondsLeft = calcTimeLeft();
if (numSecondsLeft <= 0) {
clearInterval(intervalId);
if (callback) {
callback();
}
}
label.innerHTML = numSecondsLeft + " secs";
}, 500);
}
</script>