Search code examples
javascripttimercountdown

Countdown timer using js


Need to create a countdown timer for a online quiz. Timer should start as soon as user enters web-page.

Tried this piece of code.

<
script >
    var fiveMinutes = 3600;
var display = document.getElementById('time');
var myTimer;

function startTime(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;

    function timer() {
        diff = duration - (((Date.now() - start) / 1000) | 0);
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (diff <= 0) {
            display.textContent = "TIME IS UP!";
            clearInterval(myTimer);
        }
    };
    timer();
    myTimer = setInterval(timer, 1000);
}
window.onload = function() {
    startTime(fiveMinutes, display);
}; 

Counting is required not from the current moment, but from the date specified in the startTime variable. Let's consider for your convenience that it has exactly the same format as the return value of Date.now ().

i need to get a variable, give it some value (not Date.now ()), and use it as a starting point

thanks beforehand


Solution

  • Not sure if this is what you are looking for, but this is a simple count down timer that displays the time in the window.

    const display = document.getElementById('time');
    const fiveminutes = 5 * 60 * 1000;
    
    function timer(endTime) {
      var myTimer = setInterval(function() {
        let now = new Date().getTime();
        let diff = endTime - now;
        let minutes = Math.floor(diff % (1000 * 60 * 60) / (1000 * 60));
        let seconds = Math.floor(diff % (1000 * 60) / 1000);
    
        minutes = minutes < 10 ? `0${minutes}` : minutes;
        seconds = seconds < 10 ? `0${seconds}` : seconds;
        display.textContent = minutes + ":" + seconds;
        if (diff <= 0) {
          display.textContent = "TIME IS UP!";
          clearInterval(myTimer);
        }
      }, 100);
    }
    
    window.onload = timer(new Date().getTime() + fiveminutes);
    span {
      font-family: calibri;
      font-size: 4em;
    }
    <body>
      <span id="time"></span>