Пауза / Продолжить в проекте Pomodoro Timer - PullRequest
0 голосов
/ 31 марта 2020

Я строю трекер Pomodoro, чтобы немного попрактиковаться в JavaScript. Прошло много времени с тех пор, как я начал этот проект. После этой конкретной проблемы, которая заключается в реализации функции паузы / продолжения, я отказался от проекта. Я действительно застрял. Я знаю, что программирование нелегко, и я столкнусь со многими проблемами в будущем, но я действительно не могу понять, как решить эту задачу. Я чувствую себя глупо

Вот код JavaScript:

// General Variables
let display = document.querySelector('.display');
// is the timer paused?
// let isPaused = true;
// let count = 0;
//const playPomodoro = document.querySelector('.play');
const pause = document.querySelector('.pause');
const resume = document.querySelector('.resume');
const stopPomodoro = document.querySelector('.stop');
const pomodoro = document.querySelector('#pomodoro');
const shortBreak = document.querySelector('#shortbreak');
const longBreak = document.querySelector('#longbreak')
const audioBeep = document.querySelector('#audioBeep');
const twentyFiveMinutes = 60 * 25;
const fiveMinutes = 60 * 5;
const thirtyMinutes = 60 * 30;


// Start Pomodoro timer 25 minutes
pomodoro.addEventListener('click', () => {
  startTimer(twentyFiveMinutes, display);
  stopClick(shortBreak, longBreak);
  pause.style.display = 'block';
  stopPomodoro.style.display = 'block';

});

// Start Pomodoro short break
shortBreak.addEventListener('click', () => {
  startTimer(fiveMinutes, display);
  stopClick(pomodoro, longBreak);
  pause.style.display = 'block';
  stopPomodoro.style.display = 'block';

});

// Start Pomodoro Long break
longBreak.addEventListener('click', () => {
  startTimer(thirtyMinutes, display);
  stopClick(pomodoro, shortBreak);
  pause.style.display = 'block';
  stopPomodoro.style.display = 'block';
});

// Stopping Clicks Events
function stopClick(btn1, btn2) {
  btn1.classList.add('avoid-clicks');
  btn2.classList.add('avoid-clicks');
}

// Remove .avoid-clicks class
function removeAvoidClick(btn1, btn2, btn3) {
  btn1.classList.remove('avoid-clicks');
  btn2.classList.remove('avoid-clicks');
  btn3.classList.remove('avoid-clicks');
}

// main start timer function
function startTimer(duration, display) {
  let timer = duration, min, sec;
  let countingDown = setInterval(function() {
    min = parseInt(timer / 60, 10);
    sec = parseInt(timer % 60, 10);

    min = min < 10 ? "0" + min : min;
    sec = sec < 10 ? "0" + sec : sec;

    display.innerHTML = min + ":" + sec;

    if (--timer < 0) {
      timer = duration;
    }
    // stops the counting variable when it hits zero
    if (timer == 0) {
      clearInterval(countingDown);
      display.innerHTML = "00:00";
      audioBeep.play();
      removeAvoidClick(pomodoro,shortBreak,longBreak);
    }

    // Pause the clock
    pause.addEventListener('click', () => {

    });


    // Stop the counter and set it to 00:00 when the user clicks the stop button
    stopPomodoro.addEventListener('click', () => {
      clearInterval(countingDown);
      display.innerHTML = "00:00";
      removeAvoidClick(pomodoro,shortBreak,longBreak);
    });

  }, 1000);
}

1 Ответ

0 голосов
/ 31 марта 2020

Я сохраню статус таймера в объекте, затем вы активируете таймер, который уменьшает текущее оставшееся время, и вызовете обновление пользовательского интерфейса.

let timer = {
  timeLeft: 0,
  running: 0,
};

function startTimer(duration) {
  timer.timeLeft = duration;
  if (!timer.run) {
    timer.run = true;
    run();
  }
}

function run() {
  if (timer.run) {
    timer.timeLeft -= 1;
    setTimeout(run, 1000)
  }
}

function pauseTimer() {
  timer.run = false;
}

function resumeTimer() {
  if (!timer.run) {
    timer.run = true;
    run();
  }
  update();
}

function update() {
  // everything you need to update in the UI from the timer object 
}
...