在倒计时/计时器中将时间格式化为分钟和秒钟

时间:2016-09-23 11:52:02

标签: javascript timer countdown countdowntimer

我正在制作番茄钟时钟/倒计时,但是将所选时间格式化为分钟/小时/秒会出现问题。我试图将secs变量乘以60(秒* = 60),但它弄得一团糟,我无法弄清楚如何修复它。因此,我希望它“知道”它需要从25分钟开始倒计时 - 以25:00格式,或者更多/更少(hh:mm:ss),如果用户选择+和 - 按钮。所有帮助非常感谢

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">    
</head>
<body>

<h1 id="num">25 min</h1>

<div id="status"></div>

<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>

<script src="script.js"></script>
</body>
</html>

这里是javascript:

var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);

function countDown(secs, elem) {
    var element = document.getElementById(elem); 

    secs--;
      var timer = setTimeout(function() {
    countDown(secs, elem);
    }, 1000);

    //secs *= 60;

     if(secs%60 >= 10){ //10 - if it's not a single digit number
        document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
    }
    else{
        document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
    }

    element.innerHTML = "Please wait for "+secs+" minutes";
    //if timer goes into negative numbers
    if(secs < 1){
        clearTimeout(timer);
        element.innerHTML = '<h2>Countdown complete!</h2>';
        element.innerHTML += '<a href="#">Click here now</a>';
    }
}

function increaseNumber() {
    secs += 5;
    document.getElementById('num').innerHTML = secs + ' min';
}

function decreaseNumber() {
    if(secs >= 10) {
        secs -= 5;
        document.getElementById('num').innerHTML = secs + ' min';
    }
}

2 个答案:

答案 0 :(得分:3)

你有没有理由手工做? 如果您不介意使用库,moment.js在操作时做得非常好。它重量轻,易于使用。

如果由于某些限制你必须手工完成,那么它们是什么?

供参考:

//Creates a moment. Its value is the time of creation
var timer = moment();

//add 60 seconds to the timer
timer.add(60, 's');

//Removes 1 minutes from the timer
timer.subtract(1, 'm');

来源:

Add

Substract

答案 1 :(得分:1)

试试这个countDown功能:

function countDown(secs, elem) {
    var element = document.getElementById(elem);
    element.innerHTML = "Please wait for "+secs+" minutes";

    var second = 0;
    var timer = setInterval(function(){
        var extraZero = second < 10 ? '0' : '';
        document.getElementById('num').innerHTML = secs + ":" + extraZero + second;

        if (second-- === 0) {
            second = 59;
            if (secs-- === 0){
                clearInterval(timer);
                element.innerHTML = '<h2>Countdown complete!</h2>';
                element.innerHTML += '<a href="#">Click here now</a>';
            }
        }
    }, 1000);
}

由于您倒计时秒数,因此使用setInterval代替setTimeout更有意义。