计时器达到零然后调用函数失败

Timer reaching zero then calling a function fail

我从 here 中采用了这个简单的定时器方法。

我要的很简单,就是想不出来

当计时器到达零 (0:00) 时,我想要弹出警报。同时,定时器应该在负时间继续。

所以一切正常,除了弹出窗口。知道为什么吗?

window.onload = function() {
  var minute = 0;
  var sec = 3;
  setInterval(function() {
    document.getElementById("timer").innerHTML = minute + " : " + sec;
    sec--;
    if (sec == 00) {
      minute --;
      sec = 59;
      if (minute == 0 && sec == 00) {
        alert("You failed!");
      }
    }
  }, 1000);
}
  <div class="countdown" class="failed" id="coutdown">
      Time remaining to find solution: <span id="timer">10 : 00</span>
    </div>

你的条件是在你设置sec = 59后立即检查是否sec == 0,所以条件永远不会发生。您的意思是要交换此 setter 和条件的顺序吗?

window.onload = function() {
  var minute = 0;
  var sec = 3;
  var timer = document.getElementById("timer");
  setInterval(function() {
    if (sec === 0) {
      timer.innerHTML = minute + " : " + sec;
      if (minute === 0 && sec === 0) {
        alert("You failed!");
      }
      minute--;
      sec = 60;
    } else {
      timer.innerHTML = minute + " : " + sec;
    }
    sec--;
  }, 1000);
}
<div class="countdown" class="failed" id="coutdown">
  Time remaining to find solution: <span id="timer">10 : 00</span>
</div>

您在 minute-- 之后检查分钟和秒条件,在您的代码中,这意味着 -1 不等于零。在您的代码中进行负 1 之前写一个 if 条件。

请使用 console.log("You failed!") 而不是 alert("You failed!") 以确保结果准确。

这就是我将代码完全重构为可重用函数的意思。不明白的可以评论,我会解释的。我尽量不硬编码任何计时器从 HTML.

获取其起始值

const display = document.getElementById("timer");

function toArray(domEl){
  return domEl.innerHTML.split(':').map(el => +el);
 }



function getSec(timeArr){
   if(timeArr.length > 3 || timeArr.length === 0) return;
   return timeArr.reverse().map((el, i) => el * 60 ** i).reduce((cur,accu)=> cur + accu);
 }
 
let totalSec = getSec(toArray(display)) 



setInterval(()=>{
  totalSec--;
  display.textContent = formatTime(totalSec);
},1000)


function formatTime(sec){
  const time = {hr:0, min:0, sec:0};
  time.hr = ~~(sec/3600) || 0;
  time.min = ~~(~~(sec%3600)/60);
  time.sec = ~~(sec%3600)%60;
  if(time.hr===0 && time.min===0 && time.sec ===0) alert("You Faild!")
  return `${time.hr ? time.hr + ':':''}${padTime(time.min)}:${padTime(time.sec)}`
}

function padTime(time){
   return time? String(time).padStart(2,0):0;
}
<div class="countdown" class="failed" id="coutdown">
        Time remaining to find solution: <span id="timer">0:01:05</span>
</div>