我找到了这个倒计时脚本并进行了一些基本的格式化更改,但我无法弄清楚如何让计时器在0:00停止而不是进入负数。
任何帮助将不胜感激:)
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 3;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()', 1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()', 1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs - Math.round(mins * 60);
}
</script>
</head>
<body>
<div id="timer"><font size="4"><b>You have</b></font>
<input id="minutes" type="text" style="width: 16px; border: none; background-color:transparent; color: #FF0000; font-size: 24px; font-weight: bold;"><font size="4"><b>:</b></font>
<input id="seconds" type="text" style="width: 30px; border: none; background-color:transparent; color: #FF0000; font-size: 24px; font-weight: bold;"> <font size="4"><b>to claim your free game.</b></font></div>
<script>
countdown();
</script>
答案 0 :(得分:0)
你需要检查秒和分钟是否都为零,以及它们是否从Recrement函数返回,而不是再次调用setTimeout。
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds.value < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
console.log(seconds.value);
if (minutes.value == 0 && seconds.value == 0) {
return;
}
secs--;
setTimeout('Decrement()', 1000);
}
}
我不确定你要用&lt; 59条件。尝试删除这样的逻辑:
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
minutes.value = getminutes();
seconds.value = getseconds();
console.log(seconds.value);
if (minutes.value == 0 && seconds.value == 0) {
return;
}
secs--;
setTimeout('Decrement()', 1000);
}
}
答案 1 :(得分:0)
这是一个倒计时的错误算法。这样的事情会更好
var timeout, timer;
startChrono(3*60*1000); //3 min
function startChrono (milisec) {
timeout = (new Date()).getTime() + milisec;
timer = setInterval("tick()", 1000);
}
function tick () {
var now = (new Date()).getTime();
var diff = now - timeout;
if (diff <= 0) {
clearInterval(timer);
diff = 0;
}
render(diff);
}
function render (milisec) {
var sec = Math.floor(milisec / 1000);
var min = Math.floor(milisec / 60);
sec = sec - (min*60);
document.getElementById("minutes").value = sec;
document.getElementById("seconds").value = min;
}