Countdown Timer that doesn't reset when you refresh the page?

后端 未结 3 989
星月不相逢
星月不相逢 2020-12-30 16:47

I Need to have a code for the timer that doesn\'t reset the countdown timer even you refresh the page.

I saw sample code at keith wood plug in, but

3条回答
  •  执念已碎
    2020-12-30 17:21

    If you know that the user will have local cache enabled and able to store data, you could save 2 values to localStorage, 1 for the currentTime and 1 for the targetTime. Then you compare the 2 in an interval and if currentTime > targetTime, display your message.

    Also bind to the onbeforeunload event and save the new currentTime back into localStorage. This will give you the persisted countdown you are seeking.

    Here is an example of how you can do this:

    var interval;
    let minutes = 1;
    let currentTime = localStorage.getItem('currentTime');
    let targetTime = localStorage.getItem('targetTime');
    if (targetTime == null && currentTime == null) {
      currentTime = new Date();
      targetTime = new Date(currentTime.getTime() + (minutes * 60000));
      localStorage.setItem('currentTime', currentTime);
      localStorage.setItem('targetTime', targetTime);
    }
    else{
      currentTime = new Date(currentTime);
      targetTime = new Date(targetTime);
    }
    
    if(!checkComplete()){
      interval = setInterval(checkComplete, 1000);
    }
    
    function checkComplete() {
      if (currentTime > targetTime) {
        clearInterval(interval);
        alert("Time is up");
      } else {
        currentTime = new Date();
        document.write(
         "\n  Seconds Remaining:" + ((targetTime - currentTime) / 1000) + "");
      }
    }
    
    document.onbeforeunload = function(){
      localStorage.setItem('currentTime', currentTime);
    }
    

    Note that I would've made a snippet however stackoverflow and other online IDE's are complaining about security breaches. Note that this is perfectly valid and does not breach any security. Save it as a .js and run.

    To start the "countdown" again, invoke localStorage.clear().

提交回复
热议问题