javascript倒计时器变为负数

时间:2014-09-17 13:11:24

标签: javascript html css timer

我尝试使用javascript在我的移动网站上实现倒数计时器。我已经得到了这个,但计时器变为负数,它不会停止。我希望它停在0:0。

的JavaScript

// set minutes
var mins = 5;

// calculate seconds
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);
}

HTML

<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; font-weight: bold;"> minutes and <input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;"> seconds.
</div>

我还尝试将字体颜色倒计时更改为红色,但它似乎没有改变?

<input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; **font-color:red;** font-weight: bold;">

3 个答案:

答案 0 :(得分:1)

  1. 您无条件地设置setTimeout重复。试试if( secs > 0) setTimeout(Decrement,1000)

  2. CSS为color,而不是font-color

  3. 你的代码也很乱......

    var time = 5 * 60,
        start = Date.now(),
        mins = document.getElementById('minutes'),
        secs = document.getElementById('seconds'),
        timer;
    
    function countdown() {
      var timeleft = Math.max(0, time - (Date.now() - start) / 1000),
          m = Math.floor(timeleft / 60),
          s = Math.floor(timeleft % 60);
      
      mins.firstChild.nodeValue = m;
      secs.firstChild.nodeValue = s;
      
      if( timeleft == 0) clearInterval(timer);
    }
    
    timer = setInterval(countdown, 200);
    <div id="timer">
    This is only valid for the next <strong id="minutes">-</strong> minutes and <strong id="seconds">-</strong> seconds.
    </div>

答案 1 :(得分:1)

我做了一个快速简单的计数器,你可以为自己使用

var mins=5;
var secs = mins*60;
var timerInterv = setInterval(doCountDown, 1000);
var outMins,outSecs
function doCountDown()
{
    --secs;
    if (secs<=0)
    { outMins=outSecs=0;
    clearInterval(timerInterv);
    return;
    }
    outMins = parseInt(secs/60);
    outSecs = secs%60;

    console.log("M:"+outMins+" S:"+outSecs);
}

答案 2 :(得分:0)

你必须在递减秒之前添加检查

if (secs > 0) {
        secs--;
        setTimeout('Decrement()', 1000);
    }

用于字体颜色添加颜色:您的样式中的红色表示分钟