Search code examples
javascripttimercountdown

How to prevent countdown timer from resetting when webpage is refreshed?


I am designing a website and I integrated a 5 minute countdown timer that starts when the web-page is loaded, using JavaScript. However, since I am more of a designer than a developer, I don't know how to edit the JavaScript code to make it so that the timer does not restart when the webpage is reloaded. I know I have to store the users cookies, and I've searched online, but the javascript code didnt work when I inserted the code. Would anyone here be able to help me out? Thank you!

Here is the javascript code for the 5 minute timer:

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 () {
var fiveMinutes = 60 * 5,
    display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};

Solution

  • Check this approach where the time is stored in local storage of the browser and hence on refresh will not reset:

    :HTML CODE:

    <div id="time">
    
    </div>
    

    :JS CODE:

    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;
        }
      console.log(parseInt(seconds))
      window.localStorage.setItem("seconds",seconds)
      window.localStorage.setItem("minutes",minutes)
    }, 1000);
    }
    
    window.onload = function () {
      sec  = parseInt(window.localStorage.getItem("seconds"))
      min = parseInt(window.localStorage.getItem("minutes"))
    
      if(parseInt(min*sec)){
        var fiveMinutes = (parseInt(min*60)+sec);
      }else{
        var fiveMinutes = 60 * 5;
      }
        // var fiveMinutes = 60 * 5;
      display = document.querySelector('#time');
      startTimer(fiveMinutes, display);
    };
    

    Here is the working model of the same in the codepen https://codepen.io/anon/pen/GymRNV?editors=1011

    P.S: couldn't use it here as it is a sandbox and cant access localstorage.