Search code examples
javascriptphplaraveltimercountdown

Javascript timer is already running only when it is refreshed the time is repeated, how to prevent time from being repeated


hello guys i have a project and i'm having problems in making my project. I already made a code for the exam timer and it has succeeded in counting down. the problem I experienced was when I refreshed the web page, the timer returned to the initial calculation. Please help me how to fix it. i'm using laravel framework.

var upgradeTime= {{$d->time*60}};
var seconds = upgradeTime;

function timer() {
  var days        = Math.floor(seconds/24/60/60);
  var hoursLeft   = Math.floor((seconds) - (days*86400));
  var hours       = Math.floor(hoursLeft/3600);
  var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
  var minutes     = Math.floor(minutesLeft/60);
  var remainingSeconds = seconds % 60;
  function pad(n) {
    return (n < 10 ? "0" + n : n);
  }
  document.getElementById('time').innerHTML = pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
  if (seconds == 0) {
    clearInterval(countdownTimer);
    alert('Waktu habis.');
    document.getElementById("regForm").submit();
  } else {
    seconds--;
  }
}
var countdownTimer = setInterval('timer()', 1000);

Solution

  • In order to achieve this, you can store your current time into storage and also use it from their(if available).

    var upgradeTime= {{$d->time*60}};
    var seconds = upgradeTime;
    var prevSeconds = localStorage.getItem('timerSeconds');
    
    // assign prev seconds to current seconds.
    if(prevSeconds){
     seconds = prevSeconds
    }
    
    
    function timer() {
    
      // set seconds into local storage
      localStorage.setItem('timerSeconds', seconds);
    
      var days        = Math.floor(seconds/24/60/60);
      var hoursLeft   = Math.floor((seconds) - (days*86400));
      var hours       = Math.floor(hoursLeft/3600);
      var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
      var minutes     = Math.floor(minutesLeft/60);
      var remainingSeconds = seconds % 60;
      function pad(n) {
        return (n < 10 ? "0" + n : n);
      }
      document.getElementById('time').innerHTML = pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
      if (seconds == 0) {
        clearInterval(countdownTimer);
        alert('Waktu habis.');
        document.getElementById("regForm").submit();
      } else {
        seconds--;
      }
    }
    var countdownTimer = setInterval('timer()', 1000);
    
    

    I hope this will help you.