0

I currently have a JS code that takes the amount of seconds and make a live countdown, but I would like to convert the seconds to minutes and seconds, so instead of it saying: You have to wait 602 seconds, I would like to to say: You have to wait 6 minutes and 2 seconds.

This is my javascript:

function timeleft(timeleft_sec, elementID){
    var timeleft = timeleft_sec;
    var downloadTimer = setInterval(function(){
    timeleft--;
    document.getElementById(elementID).textContent = timeleft;
    if(timeleft <= 0)
        location.reload();
    },1000);
}

This is my HTML:

You have to wait <t id="countdowntimer">602</t> seconds
<script> timeleft(602, "countdowntimer"); </script>

I have tried googling but I can only find answers where it count down from a certain date, not an amount of seconds.

  • _“I have tried googling but I can only find answers where it count down”_ - sounds like you are focussing on the wrong stuff while doing research. You don’t need a different counter, you _just_ need a way to format seconds as minutes:seconds. And with a bit of proper reseach, you could have found https://stackoverflow.com/questions/3733227/javascript-seconds-to-minutes-and-seconds – CBroe May 12 '20 at 14:26

2 Answers2

0

Use this function to convert the time -

function convertTime(seconds){
    let minutes = 0;
    while(seconds > 59) {
      minutes++;
      seconds -= 60;
    }
    return `${minutes} min ${seconds} sec`;
}

document.getElementById("time").innerText = convertTime(602);
<div id="time"></div>
Satnam Singh
  • 324
  • 2
  • 12
0

602 seconds equal to 10 minutes and two seconds So time counting is starting from 10 minutes and 2 seconds.

function timeleft(timeleft_sec, elementID) {
    var timeleft = timeleft_sec;
    var downloadTimer = setInterval(function () {
        timeleft--;
        document.getElementById(elementID).textContent =  secondToMinutes(timeleft);
        if (timeleft <= 0)
            location.reload();
    }, 1000);
}


function secondToMinutes(totalSeconds) {
    let minutes;
    let seconds;

    minutes = Math.floor(totalSeconds / 60);
    seconds = totalSeconds - minutes * 60;

    return `${minutes} minutes and ${seconds} seconds`;
}


timeleft(602, "countdowntimer");
You have to wait <t id="countdowntimer">10 minutes and 2 seconds</t>