Javascript倒计时器逻辑

时间:2016-09-01 19:43:33

标签: javascript timer logic

我对这里的逻辑有点麻烦:

var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
  seccount=seccount-1;
  if (seccount < 0) {
    seccount=59;
    return;
}
document.getElementById("sectimer").innerHTML=seccount+ " seconds!";

当它变为0时,计时器保持0为2秒,然后再次跳到58。我在函数中尝试了一些不同的东西,例如:

function sectimer() {
  seccount=seccount-1;
  if (seccount <= 0) {
    seccount=59;
    return;
}

function sectimer() {
  seccount=seccount-1;
  if (seccount < 1) {
    seccount=60;
    return;
}

但是一切都有一些变化,其中计时器在某个数字处冻结2秒然后转到我选择的数字。

我错过了什么?

2 个答案:

答案 0 :(得分:3)

回报是错误的。试试这个:

var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
    seccount--;
    if (seccount < 0) {
        seccount=59;
    }
    document.getElementById("sectimer").innerHTML=seccount+ " seconds!";
}

return导致函数立即终止,因此,当它进入条件if (seccount < 0)时(如果seccount-1),seccount 1}}正在更新为59,然后它永远不会到达下面的元素更新,但会终止于return。然后,下一次运行一秒钟后,seccount将下降到58,这显然不低于零,并跳过元素更新行。这就是为什么你觉得你失去了2秒,因为你跳过了一次元素更新: - )

答案 1 :(得分:0)

嗯,我可以这样做,如下;

function countDownFrom(n,lim = n){
  result.textContent = n + " seconds";
  setTimeout(countDownFrom,1000,n ? --n : lim-1,lim);
}
countDownFrom(5);
<p id="result"></p>