首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JavaScript中编写倒计时定时器?

如何在JavaScript中编写倒计时定时器?
EN

Stack Overflow用户
提问于 2013-12-17 02:41:08
回答 3查看 682.5K关注 0票数 280

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

网站上会有这样一句话:

“注册将在05:00分钟后关闭!”

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

我之前看过一些答案,但它们看起来都太紧张了(Date对象等)。为了我想做的事。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-17 02:50:20

我有两个演示,一个有jQuery,另一个没有。这两种方法都不使用日期函数,也不是最简单的。

代码语言: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);
};
代码语言:javascript
复制
<body>
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>

代码语言: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.text(minutes + ":" + seconds);

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

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

然而,如果你想要一个更精确的计时器,而且只需要稍微复杂一点:

代码语言:javascript
复制
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);
};
代码语言:javascript
复制
<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>

现在我们已经创建了一些非常简单的计时器,我们可以开始考虑可重用性和分离关注点。我们可以通过问“倒计时定时器应该做什么”来做到这一点。

  • 倒计时计时器是否应该倒计时?
  • 倒计时计时器是否应该知道如何在DOM上显示自己?No
  • 倒计时计时器是否应该知道在达到0时重新启动?否E221
  • 倒计时计时器是否应该为客户端提供访问剩余时间的方法?Yes

考虑到这些,让我们编写一个更好(但仍然非常简单)的CountDownTimer

代码语言:javascript
复制
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
  };
};

那么为什么这个实现比其他实现更好呢?这里有一些你可以用它做什么的例子。请注意,除了第一个示例之外,所有示例都不能由startTimer函数实现。

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

票数 601
EN

Stack Overflow用户

发布于 2013-12-17 02:44:57

你可以使用setInterval.Below很容易地创建一个定时器功能,这是你可以用它来创建定时器的代码。

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

代码语言:javascript
复制
window.onload = function() {
  var minute = 5;
  var sec = 60;
  setInterval(function() {
    document.getElementById("timer").innerHTML = minute + " : " + sec;
    sec--;
    if (sec == 00) {
      minute --;
      sec = 60;
      if (minute == 0) {
        minute = 5;
      }
    }
  }, 1000);
}
代码语言:javascript
复制
Registration closes in <span id="timer">05:00<span> minutes!

票数 29
EN

Stack Overflow用户

发布于 2013-12-17 02:54:55

如果你想要一个真正的计时器,你需要使用date对象。

计算差值。

格式化您的字符串。

代码语言:javascript
复制
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);
      })();
}

示例

Jsfiddle

计时器不是很精确

代码语言:javascript
复制
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);

JsFiddle

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20618355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档