最简单的JavaScript倒计时器? [英] The simplest possible JavaScript countdown timer?

查看:190
本文介绍了最简单的JavaScript倒计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Just wanted to ask how to create the simplest possible countdown timer.

网站上会有一句话说:


注册于05:00关闭!

"Registration closes in 05:00 minutes!"

那么,什么我想做的是创建一个简单的js倒计时器,从05:00到00:00,然后一旦结束就重置为05:00。

So, what I want to do is to create a simple js countdown timer that goes from "05:00" to "00:00" and then resets to "05:00" once it ends.

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

I was going through some answers before, but they all seem too intense (Date objects, etc.) for what I want to do.

推荐答案

我有两个演示,一个带有 jQuery ,另一个没有。既没有使用日期函数也没有使用日期函数。

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

使用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);
};

<body>
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>

< a href =http://jsfiddle.net/df773p9m/4/ =noreferrer> 使用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);
});

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

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);
};

<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>

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

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"


  • 倒数计时器是否倒计时?

  • 倒计时器是否应该知道如何在DOM上显示自己?

  • 倒数计时器是否知道在达到0时重新启动?

  • 倒计时器是否应该为客户提供一种方式来访问剩余时间?

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

因此,考虑到这些事情,我们可以写一个更好的(但仍然非常简单) CountDownTimer

So with these things in mind lets write a better (but still very simple) 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
  };
};

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

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

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

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

一个有两个不同计时器且只有一次重启的示例

启动按下按钮时倒计时

这篇关于最简单的JavaScript倒计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆