2

我想以 的格式倒数计时器,hh:mm:ss因此我使用此代码将秒数转换为所需的格式,但是当我倒数时它会显示我NaN。你能告诉我我做错了什么这是代码

<div id="timer"></div>

JS

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second parm
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    var time = hours + ':' + minutes + ':' + seconds;
    return time;
}

var count = '62';
count = count.toHHMMSS();

var counter = setInterval(timer, 1000);

function timer() {

    count--;
    if (count <= 0) {
        clearInterval(counter);
        return;
    }

    $('#timer').html(count);
}

这是 JsFiddle 链接CountDown Timer

4

3 回答 3

11

好吧,让我们看看你的代码做了什么:

  • 设置count为字符串值62
  • 将其转换为 HHMMSS,因此 nowcount等于字符串00:01:02
  • 启动计时器。
  • 在计时器第一次运行时,递减count. Erm...count是一个字符串,你不能减少它。结果不是数字。

好的,既然如此,那么如何修复它:

function formatTime(seconds) {
    var h = Math.floor(seconds / 3600),
        m = Math.floor(seconds / 60) % 60,
        s = seconds % 60;
    if (h < 10) h = "0" + h;
    if (m < 10) m = "0" + m;
    if (s < 10) s = "0" + s;
    return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);

function timer() {
    count--;
    if (count < 0) return clearInterval(counter);
    document.getElementById('timer').innerHTML = formatTime(count);
}
于 2013-08-29T09:10:31.523 回答
3
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
 if (parseInt(count) <= 0) {
    clearInterval(counter);
    return;
 }
 var temp = count.toHHMMSS();
 count = (parseInt(count) - 1).toString();
 $('#timer').html(temp);
}

http://jsfiddle.net/5LWgN/17/

于 2013-08-29T09:30:16.580 回答
0

如果您使用 jquery moment 插件。如果您不使用 jQuery 时刻,那么您可以使用@Niet 的答案中的 formatTime(seconds) 函数https://stackoverflow.com/a/18506677/3184195

var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
   start_time++;
   var formate_time = moment.utc(start_time * 1000).format('mm:ss');
      $('#Duration').text(formate_time);
   }, 1000);
});

function clear() {
    if (start_timer) clearInterval(start_timer);
}
于 2021-09-15T01:02:58.737 回答