如何在 JavaScript 中编写倒数计时器? [英] How to write a countdown timer in JavaScript?

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

问题描述

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

网站上会有一句话说:

<块引用>

注册将在 05:00 分钟后结束!"

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

我之前浏览过一些答案,但对于我想要做的事情来说,它们似乎都太紧张了(日期对象等).

解决方案

我有两个演示,一个有 jQuery,一个没有.既不使用日期函数,也尽可能简单.

使用原生 JavaScript 的演示

function startTimer(duration, display) {var timer = 持续时间、分钟、秒;设置间隔(函数(){分钟 = parseInt(timer/60, 10);秒 = parseInt(定时器 % 60, 10);分钟 = 分钟 <10 ?"0" + 分钟:分钟;秒 = 秒 <10 ?"0" + 秒:秒;display.textContent = 分钟 + ":" + 秒;if (--timer <0) {计时器 = 持续时间;}}, 1000);}window.onload = 函数 () {变量五分钟 = 60 * 5,display = document.querySelector('#time');startTimer(五分钟,显示);};

<div>注册在 <span id="time">05:00</span> 结束分钟!

jQuery 演示

function startTimer(duration, display) {var timer = 持续时间、分钟、秒;设置间隔(函数(){分钟 = parseInt(timer/60, 10);秒 = parseInt(定时器 % 60, 10);分钟 = 分钟 <10 ?"0" + 分钟:分钟;秒 = 秒 <10 ?"0" + 秒:秒;display.text(分钟 + ":" + 秒);if (--timer <0) {计时器 = 持续时间;}}, 1000);}jQuery(函数($){变量五分钟 = 60 * 5,display = $('#time');startTimer(五分钟,显示);});

但是,如果您想要一个更精确但稍微复杂一点的计时器:

function startTimer(duration, display) {var start = Date.now(),差异,分钟,秒;函数定时器(){//获取已经过去的秒数//startTimer() 被调用差异 = 持续时间 - (((Date.now() - start)/1000) | 0);//做与 parseInt 截断浮点数相同的工作分钟 = (差异/60) |0;秒 = (差异 % 60) |0;分钟 = 分钟 <10 ?"0" + 分钟:分钟;秒 = 秒 <10 ?"0" + 秒:秒;display.textContent = 分钟 + ":" + 秒;如果(差异<= 0){//添加一秒,以便从整个持续时间开始倒计时//示例 05:00 而不是 04:59开始 = Date.now() + 1000;}};//我们不想在计时器开始前等待一整秒定时器();设置间隔(定时器,1000);}window.onload = 函数 () {变量五分钟 = 60 * 5,display = document.querySelector('#time');startTimer(五分钟,显示);};

<div>注册在<span id="time"></span>结束分钟!

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

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

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

function CountDownTimer(持续时间,粒度){this.duration = 持续时间;this.granularity = 粒度 ||1000;this.tickFtns = [];this.running = false;}CountDownTimer.prototype.start = function() {如果(this.running){返回;}this.running = true;var start = Date.now(),那=这个,差异,目标;(函数定时器(){diff = that.duration - (((Date.now() - start)/1000) | 0);如果(差异> 0){setTimeout(定时器,that.granularity);} 别的 {差异 = 0;that.running = false;}obj = CountDownTimer.parse(diff);that.tickFtns.forEach(函数(ftn){ftn.call(this, obj.minutes, obj.seconds);}, 那);}());};CountDownTimer.prototype.onTick = 函数(ftn){if (typeof ftn === '函数') {this.tickFtns.push(ftn);}返回这个;};CountDownTimer.prototype.expired = function() {返回 !this.running;};CountDownTimer.parse = 函数(秒){返回 {'分钟':(秒/60)|0,'秒':(秒 % 60)|0};};

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

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

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

一个例子,有两个不同的定时器,只有一个重启

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

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

There'll be a sentence on the site saying:

"Registration closes in 05:00 minutes!"

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.

解决方案

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

Demo with 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>

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

However if you want a more accurate timer that is only slightly more complicated:

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?"

  • 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

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

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.

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

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆