Как сохранить таймер обратного отсчета JavaScript для викторины, которые не сбрасываются - PullRequest
0 голосов
/ 28 февраля 2019

Мне нужна помощь для хранения времени для этого таймера обратного отсчета, он работает нормально, но когда я нажимаю кнопку «Обновить» или назад в браузере, таймер запустит его снова, например, в 15:00, затем в примере запуска таймера будет 9:00, если янажмите обновить, он вернется к 15:00.

(function() {

    function display(notifier, str) {
      document.getElementById(notifier).innerHTML = str;
    }

    function toMinuteAndSecond(x) {
      return ~~(x / 60) + ":" + (x % 60 < 10 ? "0" : "") + x % 60;
    }

    function setTimer(remain, actions) {
      var action;
      (function countdown() {
        display("countdown", toMinuteAndSecond(remain));
        if (action = actions[remain]) {
          action();
        }
        if (remain > 0) {
          remain -= 1;
          setTimeout(arguments.callee, 1000);
        }
      })(); // End countdown
    }
    setTimer(900, {
        120: function() {
          display("notifier", "Just 1 minute to go");
        },
        50: function() {
          display("notifier", "50 seconds left");
        },

      }
    }
  );
})();
<span id="notifier"></span>

Ответы [ 2 ]

0 голосов
/ 28 февраля 2019

Здесь мы должны хранить переменную remain в локальном хранилище.переменные в локальном хранилище будут доступны даже после обновления.

Прикрепление кода, который будет работать так, как вы ожидаете.

(function() {

    function display(notifier, str) {
      document.getElementById(notifier).innerHTML = str;
    }

    function toMinuteAndSecond(x) {
      return ~~(x / 60) + ":" + (x % 60 < 10 ? "0" : "") + x % 60;
    }

    function setTimer(remain, actions) {
      var action;
      localStorage.remain = remain;
      (function countdown() {
        remain =  localStorage.remain;
        display("countdown", toMinuteAndSecond(remain));
        if (action = actions[remain]) {
          action();
        }
        if (remain > 0) {
          localStorage.remain -= 1;
          setTimeout(arguments.callee, 1000);
        }
      })(); // End countdown
    }
    setTimer(900, {
        120: function() {
          display("notifier", "Just 1 minute to go");
        },
        50: function() {
          display("notifier", "50 seconds left");
        },

      }
    }
  );
})();
0 голосов
/ 28 февраля 2019

В JS - обратите внимание, куда я поместил localStorage (который не запускается во фрагменте). Я также исправил ошибки в опубликованном коде

(function() {

  function display(notifier, str) {
    document.getElementById(notifier).innerHTML = str;
  }

  function toMinuteAndSecond(x) {
    return ~~(x / 60) + ":" + (x % 60 < 10 ? "0" : "") + x % 60;
  }

  function setTimer(remain, actions) {
    var action;
    (function countdown() {
      // add localStorage.setItem("countdown",remain)
      display("countdown", toMinuteAndSecond(remain));
      if (action = actions[remain]) {
        action();
      }
      if (remain > 0) {
        remain -= 1;
        setTimeout(arguments.callee, 1000);
      }
      else display("countdown","Done");
    })(); // End countdown
  }
  setTimer(30, { // change 30 to +localStorage.getItem("countdown") || 30;
    20: function() {
      display("countdown", "Just 20 seconds to go");
    },
    10: function() {
      display("countdown", "10 seconds left");
    },
  });
})();
<span id="countdown"></span>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...