Mohammed Sabir
Mohammed Sabir

Reputation: 167

Continuous Countdown Timer In Javascript or Jquery

I want to create a simple countdown timer in javascript or jquery.

I had implemented it using JS but what issue I am facing is if user refreshes the page then timer gets the refresh.

What I want is timer should not get the refresh. Say timer is 5 min and if user refresh pages after 1 min the timer should continue to start from 4 min instead of 5 mins. Here is code snippiet. Its refresh the timer on page refresh.

var timeoutHandle;
function countdown(minutes) {
    var seconds = 60;
    var mins = minutes
    function tick() {
        var counter = document.getElementById("timer");
        var current_minutes = mins-1
        seconds--;
        counter.innerHTML =
        current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
        if( seconds > 0 ) {
            timeoutHandle=setTimeout(tick, 1000);
        } else {

            if(mins > 1){

               // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
               setTimeout(function () { countdown(mins - 1); }, 1000);

            }
        }
    }
    tick();
}

countdown(2);
<div id="timer">2:00</div>

Upvotes: 1

Views: 2705

Answers (1)

Joschi
Joschi

Reputation: 2974

You just update the sessionStorage along with your counter and read it on starting the counter. Unfortunately the related snippet does not work on stackoverflow due to crossdomain policies - so here on codepen https://codepen.io/anon/pen/opNpVe

function countdown(seconds) {
  seconds = parseInt(sessionStorage.getItem("seconds"))||seconds;

  function tick() {
    seconds--; 
    sessionStorage.setItem("seconds", seconds)
    var counter = document.getElementById("timer");
    var current_minutes = parseInt(seconds/60);
    var current_seconds = seconds % 60;
    counter.innerHTML = current_minutes + ":" + (current_seconds < 10 ? "0" : "") + current_seconds;
    if( seconds > 0 ) {
      setTimeout(tick, 1000);
    } 
  }
  tick();
}

countdown(120);

Upvotes: 2

Related Questions