简体   繁体   中英

Countdown timer resets on a new page

I'm writing a simple battle game where two players select their characters and fight. The battle is divided into turns, each turn starts on the new page and has a timer which counts down from 99 to 0. However, I don't know how to make the timer preserve its time from the previous turn on the new page. Every time the new turn starts, the timer resets itself to 99. Is there any way to fix this problem?


<script>
      let timeLeft = 99;
      let elem = document.getElementById('timer');
      let timerId = setInterval(countdown, 1000);
      function countdown() {
          if (timeLeft == -1) {
              clearTimeout(timerId);
              doSomething();
          } else {
              elem.innerHTML = timeLeft;
              timeLeft--;
          }
        }
       function doSomething() {
          alert("Player x loses");
        }
</script>

Just set a small session variable and check for it at the beginning of each page load with an if statement. If the session variable is empty, set it to the value you want, otherwise, retain the previous value from the last time the script was run and start it from that last value.

<script>
var timeLeft;
if(!sessionStorage.getItem('timer'){
     timeLeft = 99;
} else {
     timeLeft = sessionStorage.getItem('timer');
}

      let elem = document.getElementById('timer');
      let timerId = setInterval(countdown, 1000);
      function countdown() {
          if (timeLeft == -1) {
              clearTimeout(timerId);
              doSomething();
          } else {
              elem.innerHTML = timeLeft;
              timeLeft--;
              sessionStorage.setItem('timer', timeLeft);
          }
        }
       function doSomething() {
          alert("Player x loses");
        }
</script>

For security reasons, all Internet browsers limit the ability one page has to persist or affect changes on a new page. To allow otherwise would mean that a browser could link to a new page, then access variables and other state from that new page (things like usernames, etc).

There are a few solutions but all of them are somewhat complicated. First, you could use local browser storage (it looks like someone already posted some code for thsi so I will skip a sample). This would allow you to store the time remining on the previous timer into a cookie, then your new page could load this value and resume the timer.

Another example is to use embeded frames. So instead of opening a new page in a new tab or window, you would open that page within an iframe on your parent page. With an iframe both your child and parent pages have access to the global Window object, where you can store information such as timers and other variables.

However, the best approach is to not create a new page at all. Instead, refactor your game to load each turn the same page. Use app-like components such as modals to simulate the opening of a new window. There are a ton of components out there that will accomplish this.

Use localStorage :

<script> 
let timeLeft = localStorage.getItem("timeLeft");
if(!timeLeft){
timeLeft=99;}
let elem = document.getElementById('timer'); 
let timerId = setInterval(countdown, 1000);
 function countdown() {
 if (timeLeft == -1) { 
clearTimeout(timerId); 
doSomething();
 } else { 
elem.innerHTML = timeLeft;
localStorage.setItem("timeLeft", timeLeft);
 timeLeft--; 
} } 
function doSomething() { 
alert("Player x loses"); 
} </script>

I used localStorage to set value of timeLeft because whenever you reload the page ,value of timeLeft gets reset.

Try to call variable in localStorage when page is reloaded.

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