[英]JS count down timer
我正在嘗試創建一個簡單的 JS 倒數計時器。 計時器 -- 不工作。
function setTimer() { var x = parseInt(document.getElementById("input").value); var timer = Math.floor(x * 60); var mins = Math.floor(timer / 60); var secs = Math.floor(timer % 60); var text = document.getElementById("output"); text.innerHTML = mins + ": " + secs; timer--; setTimeout('setTimer()', 1000); }
<input type="text" id="input"> <button id="btn" onClick="setTimer()"> Start </button>
計時器沒有減少。 你能幫忙嗎?
您的timer
變量沒有改變,因為它再次從輸入中獲取值。 我在下面簡化了您的代碼
<html>
<script>
var timer;
function setTimer() {
var x = parseInt(document.getElementById("input").value);
timer = Math.floor(x * 60);
handleTimer(timer);
}
function handleTimer(timer) {
var mins = Math.floor(timer / 60);
var secs = Math.floor(timer % 60);
document.getElementById("output").value = mins + " : " + secs;
timer--;
setTimeout(function () {
handleTimer(timer);
}, 1000);
}
</script>
<input type="text" id="input" placeholder="input" />
<input type="text" id="output" placeholder="output" />
<button id="btn" onClick="setTimer()">Start</button>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.