Search code examples
javascripttimercountdowncountdowntimer

Format time to minutes and seconds in countdown/timer


I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated

<!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>

and here is 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';
    }
}

Solution

  • Try this countDown function:

    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);
    }
    

    Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.