简体   繁体   中英

How to keep running my Countdown after a refresh?

I'm learning JS and I'm stuck... I want to create a countdown (it's done, my countdown is working) who keep running when the page is reloaded. I used the sessionStorage to "save" the countdown value and also to check if a sessionStorage exists when the page is loaded. The problem is, I don't know how keep running the countdown with values saved in the sessionStorage.

Could you please help me?

 class Timer { constructor(secondes, minutes) { this.secondes = secondes; this.minutes = minutes; this.button = document.getElementById("button"); this.counter = document.getElementById("counter"); this.storageCheck(); } countdown(minutes) { var seconds = this.secondes; var mins = this.minutes; var myCounter = this.counter; function tick() { var current_minutes = mins-1; seconds--; myCounter.innerHTML = current_minutes + ":" + (seconds < 10 ? "0" : "") + seconds; var duration = sessionStorage.setItem("timer", myCounter.innerHTML); if( seconds > 0 ) { setTimeout(tick, 1000); } else { if(mins > 1){ countdown(mins-1); } } } tick(); } buttonClick() { button.addEventListener("click", () => { this.countdown(this.minutes); }) } storageCheck() { if (sessionStorage.getItem("timer")) { // keep the countdown running } } } let newTimer = new Timer(60, 20); newTimer.buttonClick();
 <!DOCTYPE html> <html> <head> <title>Test Countdown</title> </head> <body> <div id="counter"></div> <button id="button">Run</button> <script type="text/javascript" src="countdown.js"></script> </body> </html>

在此处输入图片说明

You could use your storage check function to override the minutes and seconds arguments if it exists.

constructor(mins, secs) {
  this.mins = mins
  this.secs = secs
  this.checkStorage = this.checkStorage.bind(this)
  this.checkStorage(mins, secs)
}
checkStorage(mins, secs) {
  if(window.storage) { // or whatever
    this.secs = window.storage.secs
    this.mins = window.storage.mins
  }
}

Something along those lines. Basically just have the setStorage function change the values that have been set in the constructor.

You can do a simple trick by doing this

window.onload = function() {
  let minutes = sessionStorage.getItem("minutes")
  let seconds = sessionStorage.getItem("seconds")
  let newTimer = new Timer(seconds, minutes);
};

And in sessionStorage instead of storing the whole innerHtml store minutes and seconds hopefully it will solve your problem

In constructor before initializing secondes and minutes check if they are in the storage.If they dont exists then only set the this.secondes = secondes and this.minutes = minutes;

   constructor(secondes, minutes) {
        this.button = document.getElementById("button");
        this.counter = document.getElementById("counter");
        if(!this.storageCheck()){ //check if seconds are mins are stored in storage
            this.secondes = secondes; //if not set mins and sec to value passed in constructor
            this.minutes = minutes;
        }
        else{
          this.countdown(this.minutes);
        }


    }

In storage check function , check if the values are there, if there get the values and set to this.secondes and this.minutes and return true else return false

  storageCheck() {
        //if both mins and secs exists
        if (sessionStorage.getItem("mins") &&sessionStorage.getItem("secs")) {
            // keep the countdown running
            this.minutes=parseInt(sessionStorage.getItem("mins"));//get min
            this.secondes=parseInt(sessionStorage.getItem("secs"));//get secs
            return true;
        }
        else
          return false;
    }

and in countdown funciton save the values to storage

sessionStorage.setItem("mins",vm.minutes);//set current min
            sessionStorage.setItem("secs",vm.secondes);//set current sec

Try running this here : https://jsbin.com/bavexigute/1/edit?html,js,console,output

  class Timer {

    constructor(secondes, minutes) {
      this.button = document.getElementById("button");
      this.counter = document.getElementById("counter");
      if(!this.storageCheck()){ //check if seconds are mins are stored in storage
        this.secondes = secondes; //if not set mins and sec to value passed in constructor
        this.minutes = minutes;
       }
       else{
      this.countdown();
      }
    }

     countdown() {

       debugger;
       var vm=this;
        if(!(this.minutes-1<0))
           this.minutes--;
       let tick= function(){

           vm.secondes--
           if(vm.secondes==0){
              vm.secondes=59;
              vm.minutes--;
           }
           vm.counter.innerHTML =  vm.minutes + ":" + (vm.secondes < 10 ? "0" : "") + vm.secondes;
           if(vm.minutes == 0 && vm.secondes-1==0){
            vm.secondes--; 
            vm.counter.innerHTML =  vm.minutes + ":" + vm.secondes-1;

            }    
           else{
             setTimeout(tick,1000);
           }
           sessionStorage.setItem("mins",vm.minutes);//set current min
           sessionStorage.setItem("secs", vm.secondes);//set current sec
         }
        setTimeout(tick,1000);
     }    



    buttonClick() {
        button.addEventListener("click", () => {
            this.countdown();
        })
    }

    storageCheck() {
        //if both mins and secs exists
        if (sessionStorage.getItem("mins") && sessionStorage.getItem("secs")) {
            // keep the countdown running
            this.minutes=parseInt(sessionStorage.getItem("mins"));//get min
            this.secondes=parseInt(sessionStorage.getItem("secs"));//get secs
            return true;
        }
        else
          return false;
    }

}

let newTimer = new Timer(60, 20);
newTimer.buttonClick();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM