如何在番茄钟上添加分钟?

时间:2016-01-25 06:32:14

标签: javascript timer countdown

我是一名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;
}
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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

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

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