如何为番茄钟添加分钟数

How can I add minutes to a pomodoro clock?

本文关键字:添加 分钟 钟添加      更新时间:2023-09-26

我是一个JS新手,试图用最少的功能构建番茄钟。虽然我有基本的倒计时工作,但我在实现计时器的"添加额外分钟"功能时遇到了困难。

到目前为止,我在变量声明之后立即粘贴了以下内容:

// Add more minutes to timer
add.addEventListener("click", addMin);
function addMin() {
  mins += 1;
  timer.textContent = mins + ":" + "0" + currentSecs;
}

虽然这会添加倒计时前的分钟数,但它不会更新实际的倒计时分钟数。我哪里做错了?在这个问题上有一双新鲜的眼睛将不胜感激(并拯救几只小猫......

我在下面添加了 HTML 和 JS 代码:

var timer = document.getElementById("timer"),
  button = document.getElementById("button"),
  add = document.getElementById("add"),
  minus = document.getElementById("minus"),
  numOfPomodoros = 0;
// Variables for the Countdown to Work:
var mins = 25,
  secs = mins * 60,
  currentSecs = 0,
  currentMins = 0,
  comingOffBreak = false;
button.addEventListener("click", startCountdown);
function startCountdown() {
  setTimeout(countdown, 500);
}
function countdown() {
  currentMins = Math.floor(secs / 60);
  currentSecs = secs % 60;
  if (currentSecs <= 9) {
    // Add an extra zero to the seconds in order to make it look more like a clock
    currentSecs = "0" + currentSecs;
  }
  secs--;
  
  timer.textContent = currentMins + ":" + currentSecs;
  
  if (secs !== -1) {
    // Continue the countdown
    setTimeout(countdown, 1000);
  } else {
    // When countdown reaches 0...
    
    if (!comingOffBreak) {
      // If user just finished a pomodoro...
      countNumOfPomodoros();
      if (numOfPomodoros % 4 === 0) {
        button.textContent = "Start Long Break";
        resetForLongBreak();
      } else {
        button.textContent = "Start Short Break";
        resetForShortBreak();
      };
    } else {
      // If user just finished a break...
      button.textContent = "Start Pomodoro";
      resetCountdown();
    };
  };
}
function countNumOfPomodoros() {
  // Add 1 to numOfPomodoros after each pomodoro is completed
  numOfPomodoros++;
  return numOfPomodoros;
}
function resetCountdown() {
  // For new pomodoro
  mins = 25;
  secs = mins * 60;
  currentSecs = 0;
  currentMins = 0;
  comingOffBreak = false;
}
function resetForShortBreak() {
  mins = 5;
  secs = mins * 60;
  currentSecs = 0;
  currentMins = 0;
  comingOffBreak = true;
}
function resetForLongBreak() {
  mins = 30;
  secs = mins * 60;
  currentSecs = 0;
  currentMins = 0;
  comingOffBreak = true;
}
<div class="container text-center">
  <h1 id="title">POMODORO CLOCK</h1>
  <div id="timerBox">
    <span id="timer">25:00</span>
  </div>
  <br>
  <button id="minus" class="btn btn-danger">- Minute </button>
  <button id="button" class="btn btn-success">Start Pomodoro</button>
  <button id="add" class="btn btn-primary">+  Minute</button>
</div>

您正在更新方法和文本中的mins变量,而不是作为倒计时方法中考虑的变量的秒数。

我还会考虑将其重构如下:

  • 有一个变量与番茄钟的开头,
  • 有另一个变量,分钟数增加,
  • 然后使用以下伪表达式获取要显示的剩余秒数,而不使用倒计时更新变量:25 * 60 + extraMins * 60 - <current-time-in-secs> + <start-time-in-secs>