Search code examples
jquerytimersession-storage

Timer built in javascript resets when page is refreshed


I stored my timer in a session storage so it won't reset when page is refresh. But it doesn't work. I don't know why it is not working.

Here's the code of the timer and how I stored in a session storage. Maybe I have a problem in storing it?

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

function updateClock() {
  var t = getTimeRemaining(endtime);

  daysSpan.innerHTML = t.days;
  hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
  minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
  secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);


if (t.total <= 0) {
  clearInterval(timeinterval);
  swal("Oops", "Your time is up! Test will be submitted automatically.", "error");
  setTimeout(function (){
  $(document).ready(function(){$("#submitLinguistics").click();});
  clearInterval(myInterval);
  window.onbeforeunload = null;
  },3000);
 }
}

 updateClock();
var timeinterval = setInterval(updateClock, 1000);
}


sessionStorage.setItem('deadline', new Date(Date.parse(new Date() )  + (40* 60 * 1000)));
initializeClock('clockdiv', sessionStorage.getItem('deadline'));

Solution

  • It is happening because the line

    sessionStorage.setItem('deadline', new Date(Date.parse(new Date() )  + (40* 60 * 1000)));
    

    gets executed again on refresh and the deadline gets updated with the new timeStamp.

    You can do it like --

    if(!sessionStorage.getItem('deadline')){
       sessionStorage.setItem('deadline', new Date(Date.parse(new Date() )  + (40* 60 * 1000)));
    }