Search code examples
javascripttimercounter

Javascript time counter running backwards


Hi guys I have a time counter I want to count from 15 to 0. but with the current version it counts from 0 to 15. it should be running backwards. any suggestions?

  // Set the minutes
  var countDownMins = new Date().getMinutes() + 15;

  // Update the count down every 1 second
  var x = setInterval(function() {

    // Get current time
    var now = new Date().getTime();

    var distance =  now + countDownMins;

    mins = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    secs = Math.floor((distance % (1000 * 60)) / 1000);        

    // Output the results
    document.getElementById("minutes").innerHTML = mins;
    document.getElementById("seconds").innerHTML = secs;

    if (mins < 0) {
      clearInterval(x);
    }

  }, 1000);

Solution

  • A few small modifications should make this work nicely!

    You could save the countdown timer to local storage like so:

    var countDownTarget = localStorage.getItem('countDownTarget');
    if (!countDownTarget) {
        countDownTarget = new Date().getTime() + 15 * 60 * 1000;;
        localStorage.setItem('countDownTarget', countDownTarget);
    } 
    

    var countDownTarget = new Date().getTime() + 15 * 60 * 1000;
    
    function showClock(target) {
        const distance = target - new Date().getTime();
        const mins = distance < 0 ? 0: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const secs = distance < 0 ? 0: Math.floor((distance % (1000 * 60)) / 1000);        
    
        // Output the results
        document.getElementById("minutes").innerHTML = mins;
        document.getElementById("seconds").innerHTML = secs;
    }
    
    showClock(countDownTarget);
    
    // Update the count down every 1 second
    var x = setInterval(function() {
        showClock(countDownTarget);
        if (countDownTarget - new Date().getTime() < 0) {
            clearInterval(x);
        }
    }, 1000);
    Minutes: <b id="minutes"></b>
    Seconds: <b id="seconds"></b>