심재운 블로그

728x90
반응형

타이머 시분초를 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() {
    // get count from localStorage, or set to initial value of 1000
    count = getLocalStorage('count') || 100000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  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
  }
728x90
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band

본문과 관련 있는 내용으로 댓글을 남겨주시면 감사하겠습니다.

비밀글모드

loading