将时间格式化为分秒 countdown/timer

Format time to minutes and seconds in countdown/timer

我正在构建一个番茄钟 clock/countdown,但在将所选时间格式化为 minutes/hours/seconds 时遇到问题。我试图将 secs 变量乘以 60 (secs*=60),但它弄得一团糟,我不知道如何修复它。所以,我希望它 "know" 它需要从 25 分钟开始倒计时 - 采用 25:00 格式,或者 more/less(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';
    }
}

你手动做有什么原因吗? 如果您不介意使用库,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

试试这个 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);
}

由于您正在倒计时,因此使用 setIntervalsetTimeout 更有意义。