单击按钮时无法启动计时器

Can't get my timer to start when I click on my buttons

我试图让我的按钮在 select 特定时间开始倒计时。 截至目前,当我点击其中一个时,它只显示时间,并没有开始倒计时。

 <html>
     <div class="app">
        <div class="time-select">
        <button data-time="120">2 Minutes</button>
        <button data-time="300">5 Minutes</button>
        <button data-time="600">10 Minutes</button>
    </div>

    <div class="timer-container">
            <h3 class="time-display">0:00</h3>
        </div>
  </div>
 </html>


     const timeDisplay = document.querySelector(".time-display");

     const timeSelect = document.querySelectorAll(".time-select button");


     let fakeDuration = 600;
 
      timeSelect.forEach(option => {    
      option.addEventListener("click", function(){    
      fakeDuration = this.getAttribute("data-time");    
      timeDisplay.textContent = `${Math.floor(fakeDuration / 60)}:${Math.floor(fakeDuration % 
      60)}`;
      });
    });


      ontimeUpdate = () => {
        let elapsed = fakeDuration;
        let seconds = Math.floor(elapsed % 60);
        let minutes = Math.floor(elapsed / 60);

    timeDisplay.textContent = `${minutes}:${seconds}`;
};

您需要使用 setInterval() - 另外我修正了您计算分钟和秒的方式。 JS 使用毫秒 - 通常最好标准化 time-keeping/counting 以适应 JS 的现有规则。

const timeDisplay = document.querySelector(".time-display");
const timeSelect = document.querySelectorAll(".time-select button");
let fakeDuration, interval

timeSelect.forEach(option => {
  option.addEventListener("click", function() {
    clearInterval(interval)
    fakeDuration = +this.getAttribute("data-time");
      interval = setInterval( () =>  ontimeUpdate(), 1000)
  });
});


ontimeUpdate = () => {
  fakeDuration -= 1000;
  if (fakeDuration <= 0) clearInterval(interval)
  let minutes = ('0' + Math.floor(fakeDuration / 60000)).slice(-2);
  let seconds = ('0' + (fakeDuration % 60000)/1000).slice(-2);
  timeDisplay.textContent = `${minutes}:${seconds}`;
};
<div class="app">
  <div class="time-select">
    <button data-time="120000">2 Minutes</button>
    <button data-time="300000">5 Minutes</button>
    <button data-time="600000">10 Minutes</button>
  </div>

  <div class="timer-container">
    <h3 class="time-display">0:00</h3>
  </div>
</div>