Как остановить и сбросить таймер обратного отсчета? - PullRequest
2 голосов
/ 26 марта 2019

Я пытаюсь заставить мой таймер обратного отсчета выполнить следующие 4 вещи

  1. Когда нажата кнопка «Пуск», измените кнопку на «Стоп»
  2. Когда нажата кнопка «Стоп», остановите таймер
  3. Когда таймер остановлен, показать кнопку «Пуск»
  4. Когда нажата кнопка «сброс», сбросьте таймер

$(document).ready(function() {
  var counter = 0;
  var timeleft = 5;

  function nf(num) {
    var s = '0' + num;
    return s.slice(-2);
  }

  function convertSeconds(s) {
    var min = Math.floor(s / 60);
    var sec = s % 60;
    return nf(min, 2) + ' ' + nf(sec, 2);
  }

  function setup() {
    var timer = document.getElementById("timer");
    timer.innerHTML = (convertSeconds(timeleft - counter));

    var interval = setInterval(timeIt, 1000);

    function timeIt() {
      counter++;
      timer.innerHTML = (convertSeconds(timeleft - counter));
      if (counter == timeleft) {
        clearInterval(interval);
      }
    }
  }
  $("#timer-button").click(function() {
    setup();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ответы [ 2 ]

1 голос
/ 26 марта 2019

Мне недавно тоже нужно было что-то подобное. В итоге я написал для этого класс ES6.
В моем решении я использовал События, чтобы уведомить другие компоненты о таймере. Вот скрипка, в которой я отвечал вашим потребностям, но я оставил свои вызовы EventManager (), чтобы показать, что я на самом деле сделал.
Используемый EventManager - , этот . По умолчанию таймер отсчитывает с шагом 100 мс, но вы можете изменить это, вызвав startTimer () с выбранным интервалом.

class Timer {
  constructor(maxTime, startValue = 0) {
    // Actual timer value 1/10s (100ms)
    this.value = startValue;
    // Maximum time of the timer in s
    this.maxTime = maxTime * 10;
    this.timerRunning = false;
  }

  /**
   * Starts the timer. Increments the timer value every 100ms.
   * @param {number} interval in ms
   */
  startTimer(interval = 100) {
    if (!this.timerRunning) {
      let parent = this;
      this.timerPointer = setInterval(function() {
        if (parent.value < parent.maxTime) {
          parent.value++;
          //EventManager.fire('timerUpdated');
          $("span").text(parent.value / 10 + "/" + parent.maxTime / 10);
        } else {
          parent.stopTimer();
          //EventManager.fire('timeExceeded');
          $("button").text("Start");
          this.resetTimer();
          $("span").text("Countdown over");
        }
      }, interval);
      this.timerRunning = true;
    }
  }

  // Stops the Timer.
  stopTimer() {
    clearInterval(this.timerPointer);
    this.timerRunning = false;
  }

  // Resets the timer and stops it.
  resetTimer() {
    this.stopTimer();
    this.value = 0;
    $("span").text("0/" + this.maxTime/10);
    //EventManager.fire('timerUpdated');
  }

  // Resets the timer and starts from the beginning.
  restartTimer() {
    this.resetTimer();
    this.startTimer();
  }
}

let timer = new Timer(6);
$("#start-stop").click(function() {
  if (timer.timerRunning) {
    timer.stopTimer();
    $("#start-stop").text("Start");
  } else {
    timer.startTimer();
    $("#start-stop").text("Stop");
  }
});
$("#reset").click(function() {
  timer.resetTimer();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start-stop">
Start
</button>
<button id="reset">
Reset
</button>
<span>Timer: </span>
0 голосов
/ 26 марта 2019

const div = document.querySelector('div');
const btn = document.querySelector('#timerBtn');
const resetbtn = document.querySelector('#reset');

let startFlag = 0;
let count = 0;
let intervalId;
const ms = 1000;

div.textContent = count;

btn.addEventListener('click', function() {
    startFlag = startFlag + 1;

    if(startFlag%2 !== 0) { // Start button clicked;
        btn.textContent = 'Stop';
        startTimer();
    } else {
        btn.textContent = 'Start';
        stopTimer();
    }
});

resetbtn.addEventListener('click', function() {
    count = 0;
    div.textContent = count;
});

function startTimer() {
    intervalId = setInterval(() => {
        count = count + 1;
        div.textContent = count;
    }, 1000);
}

function stopTimer() {
    clearInterval(intervalId);
}
<div></div>
<button id="timerBtn">Start</button>
<button id="reset">Reset</button>
...