简体   繁体   中英

javascript timer and sessionStorage

I have the following issue. I have a timer function and it takes a parameter, the number of second. When passing it directly, it works without flaws. However, I need to use sessionStorage for multiple reasons, and when I retrieve the variable from the sessionStorage before passing it to the timer function, it multiplies by 10 the number of seconds passed in parameters. I can't figure why it has this behavior. I wrote a minimal example to illustrate my issue:

function countdown(time_p) {
  var saved_countdown = sessionStorage.getItem('saved_countdown');
  var time;

  if (saved_countdown == null) {
    // Set the time we're counting down to using the time allowed
    var new_countdown = new Date().getTime() + (time_p + 2) * 1000;
    time = new_countdown;
    sessionStorage.setItem('saved_countdown', new_countdown);
  } else {
    time = saved_countdown;
  }
  // Update the count down every 1 second
  var x = setInterval(() => {

    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the allowed time
    var distance = time - now;

    // Time counter
    var counter = Math.floor(distance / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = counter + " s";

    // If the count down is over, write some text 
    if (counter <= 0) {
      clearInterval(x);
      sessionStorage.removeItem('saved_countdown');
      sessionStorage.removeItem('max_time');
      document.getElementById("demo").innerHTML = "EXPIRED";
    }
  }, 1000);
}

$("#confirm_settings").click(function() {
  var time = $("#time").val();
  console.log("time entered" + time);
  sessionStorage.setItem('max_time', time);
  time = sessionStorage.getItem('max_time'); // multiply the time entered by 10 ...
  // time = 42; // works well
  console.log("time = " + time);
  countdown(time);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<p id="demo"> </p>
<label for "time"> Time limit :</label>
<input type="text" id="time" placeholder="enter a duration (s)"> <br>
<button type="button" id="confirm_settings">OK</button>

window storage saves strings. You need to cast them to ints:

function countdown(time_p) {
  var time = sessionStorage.getItem('saved_countdown');

  if (time) {
    time = +time; // cast the string to number
  }
  else {
    // Set the time we're counting down to using the time allowed
    var new_countdown = new Date().getTime() + (time_p + 2) * 1000;
    time = new_countdown;
    sessionStorage.setItem('saved_countdown', new_countdown);
  } 

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