最简单的JavaScript倒计时器?

Bar*_*tek 217 javascript timer countdown countdowntimer

只是想问一下如何创建最简单的倒数计时器.

网站上会有一句话说:

"注册于05:00关闭!"

所以,我想要做的是创建一个简单的js倒计时器,从"05:00"到"00:00",然后一旦结束就重置为"05:00".

我以前经历过一些答案,但是对于我想做的事情,它们看起来都太强烈了(Date对象等).

rob*_*bmj 432

我有两个演示,一个有jQuery一个,一个没有.既没有使用日期功能,也没有使用日期功能.

用vanilla JavaScript演示

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
Run Code Online (Sandbox Code Playgroud)
<body>
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>
Run Code Online (Sandbox Code Playgroud)

用jQuery演示

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});
Run Code Online (Sandbox Code Playgroud)

但是,如果您想要一个更复杂的更准确的计时器:

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
Run Code Online (Sandbox Code Playgroud)
<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>
Run Code Online (Sandbox Code Playgroud)

现在我们已经制作了一些非常简单的计时器,我们可以开始考虑可重用性和分离问题.我们可以通过询问"倒计时器应该做什么来做到这一点"来做到这一点.

  • 倒数计时器倒数吗?
  • 倒数计时器是否应该知道如何在DOM上显示自己?没有
  • 如果倒数计时器知道在达到0时重新启动吗?没有
  • 倒计时器是否应该为客户提供一种方式来访问剩余的时间?

所以记住这些事情让我们写得更好(但仍然非常简单) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};
Run Code Online (Sandbox Code Playgroud)

那么为什么这种实现比其他实现更好?以下是您可以使用它做些什么的一些示例.请注意,除了第一个示例之外的所有示例都无法通过startTimer函数实现.

以XX:XX格式显示时间并在到达00:00后重新启动的示例

以两种不同格式显示时间的示例

一个示例,它有两个不同的计时器,只有一个重启

按下按钮时启动倒计时器的示例

  • @timbram起初对我来说看起来很奇怪,直到我意识到`var`声明后面的逗号分隔了不同的声明.所以`minutes`和`seconds`只是声明(但未初始化)变量.所以`timer`只是等于`duration`参数,仅此而已. (6认同)
  • 你如何添加重置选项?还有暂停和恢复?我尝试添加一个字段this.reset,并在闭包中检查.但时钟仍在继续. (3认同)
  • 你是男人!这正是我想要的.谢谢!还有一件事:如何在分钟前添加"0",所以它显示"04:59",而不是"4:59"? (2认同)
  • `分钟 = 分钟 &lt; 10 ? “0”+ 分钟:分钟;` (2认同)
  • @SinanErdem我写了一些代码来做到这一点.我可以在今天晚些时候将该代码添加到答案中.完成后我会ping你. (2认同)

coc*_*cco 22

如果你想要一个真正的计时器,你需要使用日期对象.

计算差异.

格式化字符串.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

不那么精确的计时器

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);
Run Code Online (Sandbox Code Playgroud)

的jsfiddle


小智 13

您可以使用setInterval轻松创建计时器功能.Below是可用于创建计时器的代码.

http://jsfiddle.net/ayyadurai/GXzhZ/1/

window.onload = function() {
  var hour = 2;
  var sec = 60;
  setInterval(function() {
    document.getElementById("timer").innerHTML = hour + " : " + sec;
    sec--;
    if (sec == 00) {
      hour--;
      sec = 60;
      if (hour == 0) {
        hour = 2;
      }
    }
  }, 1000);
}
Run Code Online (Sandbox Code Playgroud)
Registration closes in <span id="timer">05:00<span> minutes!
Run Code Online (Sandbox Code Playgroud)

  • 将500更改为1000似乎使其准确. (4认同)
  • 不能准确地代表每一秒,它的倒数太快了. (3认同)
  • 看来“5:60”永远不应该成为现实。 (2认同)