如何在JavaScript中编写倒计时器?[已关闭]

gg58donl  于 2022-12-21  发布在  Java
关注(0)|答案(3)|浏览(133)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

六年前关闭了。
去年,机构群体审查了是否重新讨论此问题,并将其关闭:
原始关闭原因未解决
Improve this question
只是想问一下如何创建最简单的倒计时器。
网站上会有一句话:
“报名将在05:00分截止!”
所以,我想做的是创建一个简单的js倒计时器,从“05:00”到“00:00”,然后在结束后重置为“05:00”。
我之前经历过一些答案,但它们对于我想做的事情来说似乎都太过强烈(日期对象等)。

cngwdvgl

cngwdvgl1#

我有两个演示,一个有jQuery,一个没有。两个都不使用日期函数,而且都很简单。
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);
});
    • 但是,如果您想要一个更精确的计时器,只是稍微复杂一些:**

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

  • 倒计时定时器是否应该倒计时?
  • 倒计时计时器应该知道如何在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
  };
};

那么为什么这个实现比其他的更好呢?这里有一些例子来说明你可以用它来做什么。注意,除了第一个例子之外,所有的例子都不能用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

jhiyze9q

jhiyze9q2#

使用setInterval可以很容易地创建一个定时器功能。下面是可以用来创建定时器的代码。
http://jsfiddle.net/ayyadurai/GXzhZ/1/

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);
}
Registration closes in <span id="timer">5:00</span>!
xxb16uws

xxb16uws3#

如果你想要一个真正的计时器,你需要使用日期对象。
计算差值。
设置字符串的格式。

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);
      })();
}
    • 示例**

∮ ∮ ∮ ∮
不太精确的计时器

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

∮ ∮ ∮ ∮

相关问题