재우니의 블로그

javascript : 타이머 timer 시분초를 localStorage 와 함께 사용

 

 

 

https://stackoverflow.com/questions/43134829/wants-javascript-countdown-to-continue-from-where-it-was-even-after-refresh

 

wants javascript countdown to continue from where it was even after refresh

I am designing a javaScript countdown for 3 hours using the below code

 

 localStorage를 사용하려는 경우 :

<div>
  <img src="https://playcode.io/static/img/logo.png" 
       alt="PlayCode logo"> 
  <span id="msg"></span>
   <div id="timer"></div>
</div>
// properties
  var count = 0;
  var counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // localStorage 에서 count 가져오기, 초기값은 20초
    count = getLocalStorage('count') || 20;
    counter = setInterval(timer, 1000); //1초마다 카운팅
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    count = setLocalStorage('count', count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours +  "hours "  + minutes +  "minutes and "   + seconds +  "  seconds left to complete this transaction"; // watch for spelling
  }