Keep timer (setInterval) running while reloading page

Keep timer (setInterval) running while reloading page

When you reload a page, the entire page context including all running JS is completely destroyed. You cannot keep a setInterval() running while its host page is reloaded.

You can create a signal for the new page to start the interval going again itself using a cookie, query parameter or local storage value (query parameter is probably the most appropriate). If you go this way, then you need to code the page to look for a specific query parameter and if it finds it, then the page should start the designated setInterval() itself. You can even pass some data in the query parameter (such as how much more time until the next interval should fire, etc...).

Another option is to not actually reload the page, but instead to refresh the content manually by getting new content via an ajax call and then inserting it into the current page. This allowed the current page context and running interval timers to continue running.

 

I have a javascript timer everytime I refresh the page the timer wil reset

You need to learn how things work: when you refresh a page, your request a new copy of it from the server, and that discards everything that has been done to the page so far - and that includes timers. You can't start a timer that works even when the page it is running on has been discarded for any reason, unless you run the timer at the server instead of the client.

You could use a cookie to save the current timer value, and update that every time the timer ticks but that's a messy solution at best, and prone to "losing time" unless you are very careful how you do it. 

 

 

After refresh setTimeout will work or Not?

I have script like below. if i refresh a page before (3 Minutes)setTimeout, get_details function call will work or not?

setTimeout(function() {
    get_details(user);
}, 18000);

 回答

If you refresh while the timer is running it will start all over again when the page reloads.

So to answer your question, yes the get_details() function will be called after the refresh but only after the full 3 minutes has elapsed since the refresh occurred.

 

Timer is resetting on refresh how to avoid that?

Whenever a page is readloaded, the entire context of the old page is destroyed and an entirely new context is created. You can't keep a timer from one page load running on the next page load.

If you need to save some state from one page load to the next and then in the next page load examine that state and decide exactly how to set up the initial page to match what was previously going on, then you can save state between page loads in either HTML5 local storage or in a cookie.

The other possibility is to NOT reload your page and instead update the contents of the page dynamically using ajax and javascript. That way your existing timer would just keep running because there would be no page reload at all.

If all you're trying to do with your timer is show how much time is left in some countdown, you can set the countdown zero time into HTML5 local storage and when the reloaded page loads, it can check the time set in local storage and start the countdown timer to match the time it was previously set for.

Use cookie, or if HTML5 then local/session storage to save state.

HTML

<a href="#" onclick="SaveTime()">Save Current Time</a> | 
<a href="#" onclick="retrieveTime()">Retrieve Saved Time</a>

<div id="result"></div>  

JAVASCRIPT

function SaveTime(){
var date = new Date();
var timeObj = { sec:date.getSeconds(), min:date.getMinutes(), hr:date.getHours() };
localStorage.setItem("timeObj", JSON.stringify(timeObj));
$('#result').append(JSON.stringify(timeObj)+' -- > Saved<br />' );
}

function retrieveTime(){
var timeObj = JSON.parse(localStorage.getItem("timeObj"));
//You have the time with you now
//You have the time with you now
$('#result').append(timeObj.hr+':'+timeObj.min+':'+timeObj.sec+' --> Retrieved<br />');
}

Its just a basic example to save timer in local storage on click. Modify it and call the javascript function in timer regularly.

 

 

How to make js timer not to restart when reload page?

You can set the value of the time before the window get unloded in the localstorage like this

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="controls">
      <button onclick="start()">Start</button>
      <button onclick="pause()">Pause</button>
      <button onclick="stop()">Restart</button>
    </div>
    <div class="stopwatch">60:00:00</div>


  </body>
</html>
     var ms = 0,
        s = 0,
        m = 60;
      var isCountingDown = false;
      var timer;

      window.addEventListener("load", function () {
        if (window.localStorage.getItem("time") !== null) {
          let obj = JSON.parse(window.localStorage.getItem("time"));
          s = obj["s"];
          ms = obj["ms"];
          m = obj["m"];

          stopwatchEl.textContent = `${m}:${s}:${ms}`;
          start();
        }
      });

      window.addEventListener("beforeunload", function () {
        if (isCountingDown == true) {
          pause();
          let obj = {
            ms: ms,
            s: s,
            m: m,
          };
          window.localStorage.setItem("time", JSON.stringify(obj));
        }
      });

      var stopwatchEl = document.querySelector(".stopwatch");
      var lapsContainer = document.querySelector(".laps");

      function start() {
        if (!timer) {
          isCountingDown = true;
          timer = setInterval(run, 10);
        }
      }

      function run() {
        stopwatchEl.textContent =
          (m < 10 ? "0" + m : m) +
          ":" +
          (s < 10 ? "0" + s : s) +
          ":" +
          (ms < 10 ? "0" + ms : ms);
        ms--;
        if (ms < 0) {
          ms = 99;
          s--;
        }
        if (s < 0) {
          s = 59;
          m--;
        }
        if (m == 0 && s == 0 && ms == 0) {
          pause();
          var figyelmeztetes = confirm("Lejárt az idő!");
        }
        stopwatchEl.textContent =
          (m < 10 ? "0" + m : m) +
          ":" +
          (s < 10 ? "0" + s : s) +
          ":" +
          (ms < 10 ? "0" + ms : ms);
      }

      function pause() {
        clearInterval(timer);
        timer = false;
      }

      function stop() {
        var figyelmeztetes = confirm(
          "Vigyázz!!! Ezzel a számláló visszaáll 60 percre!"
        );
        if (figyelmeztetes == true) {
          clearInterval(timer);
          timer = false;
          ms = 0;
          s = 0;
          m = 60;
          stopwatchEl.textContent =
            (m < 10 ? "0" + m : m) +
            ":" +
            (s < 10 ? "0" + s : s) +
            ":" +
            (ms < 10 ? "0" + ms : ms);
        }
      }

 

 

Countdown timer - make it persistent even after refresh or reload

回答1

You can try using localStorage as follows:

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;

        // update the persisted time interval
        localStorage.setItem('timeLeft', i);

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

    }, 1000);
}

window.onload = function () {
    let timeInterval = 100;
    //check if you have the last counter value
    let timeLeft = localStorage.getItem('timeLeft');
    if (isNaN(timeLeft)) {
        //save the current interval
        localStorage.setItem('timeLeft', timeInterval);
    } else if (timeLeft == 0) {
        //save the current interval
        localStorage.setItem('timeLeft', timeInterval);
    } else {
        // take the last saved value
        timeInterval = timeLeft;
    }

    countDown(timeInterval, function () {
        $('#myModal').modal('show');
    });
};

 

 回答2

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');
  });
};

 

How to make countdown timer not reset when refresh the browser?

Try to use session storage :

// Store
sessionStorage.setItem("key", "value");
// Retrieve
document.getElementById("result").innerHTML=sessionStorage.getItem("key"); 

Update

Example :

<head>

</head>
<body>
    <div id="divCounter"></div>
    <script type="text/javascript">
    if (sessionStorage.getItem("counter")) {
      if (sessionStorage.getItem("counter") >= 10) {
        var value = 0;
      } else {
        var value = sessionStorage.getItem("counter");
      }
    } else {
      var value = 0;
    }
    document.getElementById('divCounter').innerHTML = value;

    var counter = function () {
      if (value >= 10) {
        sessionStorage.setItem("counter", 0);
        value = 0;
      } else {
        value = parseInt(value) + 1;
        sessionStorage.setItem("counter", value);
      }
      document.getElementById('divCounter').innerHTML = value;
    };

    var interval = setInterval(counter, 1000);
  </script>
</body>

 

 

 

 

 

 

 

 

 

posted @ 2021-09-23 16:34  ChuckLu  阅读(1040)  评论(0编辑  收藏  举报