【发布时间】:2015-12-13 11:10:21
【问题描述】:
我是 JS 的新手,我一直在试图弄清楚是什么导致我的倒计时计时器不倒计时。用户以 00:00:00 格式分钟、秒和毫秒输入时间。之后,我将该格式转换为秒以开始倒计时过程。我认为计算很好,但某些东西并没有导致它不应该表现得像它应该的那样。我已经测试并看到代码在输入时间和显示在输出中运行。我看到倒计时同时减少了秒和毫秒,但它应该从 10:00:00 到 09:59:99 .. 09:59:98 ... 基本上秒不会改变,直到毫秒零。所以 09:59:00 将是 09:58:99... 非常感谢任何帮助。我一直在做这个并且被卡住了。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var running = 0; //Glob variable for starting/pausing timer
function startPause(){
var time = document.getElementById("timeEntered").value; //Not sure if needed but I just have the time entered be converted to seconds.
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 0){ //If off, turn it on.
running = 1;
countDown();
document.getElementById("startPause").innerHTML = "Start/Stop";
}else{
running = 0;
document.getElementById("startPause").innerHTML = "Resume";
}
}
function countDown() {
var time = document.getElementById("timeEntered").value; //Take user input and convert 00:00:00 format to seconds.
var a = time.split(":");
if(!timeToSeconds)
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 1){ //When user clicks start it will calculate the minutes, seconds, and milliseconds.
var minutes = Math.floor(timeToSeconds / 60);
var seconds = timeToSeconds % 60;
var milli = timeToSeconds % 100;
if(minutes <= 9) { //Add leading zeroes to display countdown in 00:00:00 format.
minutes = "0" + minutes;
}
if(seconds <= 9) {
seconds = "0" + seconds;
}
if(milli <= 9) {
milli = "0" + milli;
}
timeToSeconds--; //Decrement the time entered.
console.log(timeToSeconds);
document.getElementById("output").innerHTML = minutes + ":" + seconds + ":" + milli //Display the time 00:00:00 format.
if(timeToSeconds !== -1){
setTimeout('countDown()',100);
}
if(timeToSeconds == 0){ //When time is 00:00:00 the message will show.
document.getElementById("output").innerHTML = "The time is over."
}
}
}
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="mainCont">
<input type="text" id="timeEntered">
<p>
<button id="startPause" onclick="startPause()">Start/Stop</button>
</p>
<div id="output">00:00:00</div>
</div>
</body>
</html>
【问题讨论】:
-
这个太模糊了,无法回答,你应该描述会发生什么,你期望会发生什么,你尝试了什么。
-
请学习如何使用 JavaScript 控制台并调试您的代码,
console.log(timeToSeconds)会显示您的问题。价值永远不会改变。因为你不断地从你的input那里得到它,它是静态的。正在调用函数,但值永远不会改变。 -
Here is the code with the applied fix。这是您所期望的还是它仍然有问题(我假设您不希望中间值按原样增加)?如果是这样,请描述问题所在以及您的预期。
-
感谢 Spencer 的帮助...但是倒计时应该像秒表一样工作,但相反。在毫秒递减并且在秒可以改变之前,毫秒必须首先从 100-0 达到,就像这样。 10:00:00... 09:59:99... 09:59:98.. 当然这会快速模拟到 09:59:00.. 09:58:99。现在它同时减少了秒和毫秒。
-
@user5544269 这是因为
mili或seconds都没有乘以任何数字,所以除了模运算符之外它们将是相同的值。我在下面添加了我的答案。
标签: javascript html