-->

Timer refreshes after browser page is reloaded - J

2020-02-16 01:14发布

问题:

I built a countdown timer with the help of people from this platform a few days back. I thank them all for that. But I have run into another issue. When I refresh the page, the whole timer is reset and everything goes back to normal. I looked it up and realised I need to store seconds in something called the local storage of the browser. But how to implement it into my code is the problem. Similar issues like mine have different ways of solving this. I tried changing it to theirs but had the timer not showing when the page is refreshed and the button enabled when it must be disabled. Please help.

HTML

<div class="mdl-card__actions mdl-card--border">
                        <div>Timer : <span  id="time1">05:00</span></div>
                            <div class="mdl-grid">

                            <div class="mdl-layout-spacer"></div>

                                <button id="coinbtn1" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdl-button--colored">
                            50 coins 
                            </button>
                            <div class="mdl-layout-spacer"></div>
                            </div>

                        </div>

JS

$("#coinbtn1").click(function() {

    var uid = firebase.auth().currentUser.uid;

    var coinRef = firebase.database().ref().child('users_coins').child(uid).child('coins');

    var counter = 50;

    coinRef.transaction(function (counter) {
      return (counter || 0) + 50;
    }); 

  var fiveMinutes = 60 * 5,
    display = document.querySelector('#time1');
  startTimer1(fiveMinutes, display);

});

function startTimer1(duration, display) {
  var timer = duration,
    minutes, seconds;


  var intervalFn1 = function() {

    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if(timer-1 != 0){
    document.getElementById('coinbtn1').disabled = true;
  }

  if (timer-1 === 0) {

    clearInterval(myVar1);
    document.getElementById('coinbtn1').disabled = false;

  }

  --timer;


  }

  myVar1 = setInterval(intervalFn1, 900);

  intervalFn1();

}

Code used before...

$("#coinbtn1").click(function() {

    var uid = firebase.auth().currentUser.uid;

    var coinRef = firebase.database().ref().child('users_coins').child(uid).child('coins');

    var counter = 50;

    coinRef.transaction(function (counter) {
      return (counter || 0) + 50;
    }); 

  /* var fiveMinutes = 60 * 5,
    display = document.querySelector('#time1');
  startTimer1(fiveMinutes, display); */

  $time_limit = "2016-08-14 00:10:00"
var d = new Date($time_limit);
var hours = d.getHours(); //00 hours
var minutes = d.getMinutes(); //10 minutes
var seconds = 60 * minutes; // 600seconds

if (typeof(Storage) !== "undefined") {
  if (localStorage.seconds) {
    seconds = localStorage.seconds;
  }
}

function secondPassed() {
  var minutes = Math.round((seconds - 30) / 60);
  console.log(minutes);
  var hours = Math.round((minutes) / 60);
  var remainingSeconds = seconds % 60;
  if (remainingSeconds < 10) {
    remainingSeconds = "0" + remainingSeconds;
  }
  if (typeof(Storage) !== "undefined") {
    localStorage.setItem("seconds", seconds);
  }
  document.getElementById('time1').innerHTML = "0" + minutes + ":" + remainingSeconds;

  if (seconds == 0) {
    clearInterval(myVar);
    document.getElementById('time1').innerHTML = "Time Out";
    if (typeof(Storage) !== "undefined") {
      localStorage.removeItem("seconds");
    }
  } else {
    seconds--;
    console.log(seconds);
  }

}
var myVar = setInterval(secondPassed, 900);

});

回答1:

You'll probably want to save to the localStorage every time your timer ticks. Something like this:

localStorage.setItem('timerValue', timerValue); // assume timerValue is defined

When the user opens the page, you'll need to retrieve said item:

var time = localStorage.getItem('time');

Edit:

I think your problem might be with the following code:

if (localStorage.seconds) {
  seconds = localStorage.seconds;
}

You're checking whether localStorage has a property called seconds before setting it, but the first time you try to save seconds this property will always be undefined.