我正在尝试以MM:SS格式实现倒数计时器,其中03:00
会递减为02:59
,依此类推。
当用户选择60、180或300秒(1、3、5分钟)的选项值时,计时器将设置为该值并每秒倒数。
function qs(selector) {
return document.querySelector(selector);
}
function startTimer() {
let timer = qs("select");
remainingSeconds = timer.options[timer.selectedIndex].value;
let timerDisplay = formatTimer(remainingSeconds);
qs("#time").innerHTML = timerDisplay;
timerId = setInterval(advanceTimer, 1000);
}
function formatTimer(remainingSeconds) {
let minutes = Math.floor(remainingSeconds / 60);
let seconds = remainingSeconds % 60;
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
return minutes + ":" + seconds;
}
function advanceTimer() {
if (remainingSeconds = 0) {
clearInterval(timerId);
//end the game logic here
console.log("times up!");
} else {
qs("#time").innerHTML = remainingSeconds--;
}
}
window.onload = function(){
startTimer();
}
<select>
<option selected>30
<option>60
</select>
<div id="time"></div>
[现在,计时器的行为是,例如,它的开始于3:00
,但随后1秒钟后递减到00:00
。如何调整函数的行为,以使其减少到期望的输出。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Test Timer</title>
</head>
<body>
<span id="spanTimeLeft"></span> seconds left
</body>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("body").on('click keypress', function () {
ResetThisSession();
});
});
var timeInSecondsAfterSessionOut = 600; // to change the session time out, change this value. Must be in seconds.
var secondTick = 0;
function ResetThisSession() {
secondTick = 0;
}
function StartThisSessionTimer() {
secondTick++;
var timeLeft = ((timeInSecondsAfterSessionOut - secondTick) / 60).toFixed(0); // in minutes
timeLeft = timeInSecondsAfterSessionOut - secondTick;
$("#spanTimeLeft").html(timeLeft);
tick = setTimeout("StartThisSessionTimer()", 1000);
}
StartThisSessionTimer();
</script>
</html>