0

I need a timer of 25 minutes which will count until 0. I've found many tutorials but every tutorial I've found lacks an explanation.

This is the link I found most useful. Can somebody explain how does it work? The simplest possible JavaScript countdown timer?

EDIT: I don't want to copy&paste the code. I want to understand it.

martinkzn
  • 103
  • 2
  • 9

1 Answers1

0

Based on that answer this is what you are looking for :

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
//this is where you can modifies the time amount.
    var twentyfiveminutes = 60 * 25,
        display = document.querySelector('#time');
    startTimer(twentyfiveminutes, display);
};
<body>
    <div>Registration closes in <span id="time">25:00</span> minutes!</div>
</body>

So to know more the person how created this code did the next steps :

  1. a function startTimer(duration, display) this function take two parameter first the time on minutes and the the html element for output.
  2. using setInterval() he repeated the function every one second.
  3. then he initial tree variables timer = duration and minutes = duration/60 and seconds = duration%60.
  4. then he check if the value of minute or second are bigger then 10. to add zero if not.
  5. and at last he take one second of timer and check if it value is bigger then 0 else return it to first state.
  6. and he repeat that until the value of time is 0;
M0ns1f
  • 2,705
  • 3
  • 15
  • 25