我正在JavaScript中製作一個計時器,並且在啓動和停止計時器時遇到了一些麻煩,而無法在計時器再次啓動時跳過它。我已經放入一個布爾(isPaused)來暫停和播放setInterval,但是當我播放定時器跳過任何時間長度時已經暫停。我試着回想起setInterval函數,並試着重置決定倒計時時間的變量(timeLeft)。當我暫停播放它時,timeLeft變量是相同的,所以我不確定它爲什麼會這樣跳。暫停和播放按鈕上的setInterval()點擊
我的HTML:
<div class="container">
<div class="row">
<div class="col-xs-6">
<button id="start-button">Start Timer</button>
<button id="pause-button">Pause Timer</button>
<button id="play-button">Play Timer</button>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<span id="display-minutes"></span>
<span id="display-seconds"></span>
<span id="display-milli"></span>
</div>
</div>
</div>
和我的JavaScript:
var minutes = 25;
var seconds = 0;
var milliseconds = 0;
var endTime = 0;
var timeLeft = 0;
var dateAtPause = 0;
var isPaused = false;
$('#display-minutes').html(minutes);
$('#display-seconds').html(seconds);
$('#display-milli').html(milliseconds);
//calculate time remaining between now and endTime
function timeRemaining() {
timeLeft = Date.parse(endTime) - Date.parse(newDate());
var milliseconds = Math.floor(timeLeft % 1000);
var seconds = Math.floor((timeLeft/1000) % 60);
var minutes = Math.floor(timeLeft/1000/60);
var total = timeLeft;
return {
'milliseconds': milliseconds,
'seconds': seconds,
'minutes': minutes,
'total': total,
};
}
function updateClock() {
if (!isPaused) {
var time = timeRemaining();
$('#display-minutes').html(time.minutes);
$('#display-seconds').html(time.seconds);
$('#display-milli').html(time.milliseconds);
if (time.total <= 0) {
clearInterval(timeInterval);
};
};
};
$('#start-button').click(function() {
//set time (var minutes) minutes from now
var startTime = new Date();
endTime = new Date(startTime.setMinutes(startTime.getMinutes() + minutes));
updateClock();
var timeInterval = setInterval(updateClock, 1000);
});
$('#pause-button').click(function() {
isPaused = true;
dateAtPause = new Date();
console.log(timeLeft);
});
$('#play-button').click(function() {
isPaused = false;
var timeInterval = setInterval(updateClock, 1000);
console.log(timeLeft);
});
謝謝!我把你的概念和運行,讓一切變得更簡單,謝謝! – Davez01d