Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Countdown timer - make it persistent even after refresh or reload

Tags:

javascript

I have a html page where there is counter starts on page loading. But the problem is if someone refresh or reloads the page the counter restarts. I dont know how to use local storage or cookies to make sure my counter does not reset upon reload. I am aware of the similar questions available here but my issue is i want local storage to be part of a function (countDown()).

Here is the code I tried:

<script>

    var timer;

    function countDown(i, callback) {
        //callback = callback || function(){};
        timer = setInterval(function() {
            minutes = parseInt(i / 60, 10);
            seconds = parseInt(i % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            document.getElementById("displayDiv ").innerHTML = "Time (h:min:sec) left for this station is  " + "0:" + minutes + ":" + seconds;

            i-- || (clearInterval(timer), callback());
        }, 1000);
    }

    window.onload = function() {
        countDown(60, function() {
            $('#myModal').modal('show');
        });
    };
</script>
like image 773
ms kk rr Avatar asked Sep 05 '26 17:09

ms kk rr


1 Answers

First, persist your current counter value to the session storage (with a specific key) at each iteration. You may only persist/update the value when the counter is greater than 0, and then clear the storage key once counter reached 0.

const COUNTER_KEY = 'my-counter';

function countDown(i, callback) {
  //callback = callback || function(){};
  timer = setInterval(function() {
    minutes = parseInt(i / 60, 10);
    seconds = parseInt(i % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    document.getElementById("displayDiv").innerHTML = "Time (h:min:sec) left for this station is  " + "0:" + minutes + ":" + seconds;

    if ((i--) > 0) {
      window.sessionStorage.setItem(COUNTER_KEY, i);
    } else {
      window.sessionStorage.removeItem(COUNTER_KEY);
      clearInterval(timer);
      callback();
    }
  }, 1000);
}

Then on the window.onload function, first check if there is a value under the above key on the session storage. If a value is there, start the countdown from that value. Otherwise, start from your default value (60).

window.onload = function() {
  var countDownTime = window.sessionStorage.getItem(COUNTER_KEY) || 60;
  countDown(countDownTime, function() {
    $('#myModal').modal('show');
  });
};
like image 78
Udith Gunaratna Avatar answered Sep 07 '26 06:09

Udith Gunaratna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!