带有重复和延迟的普通 JS 倒计时 [英] Plain JS countdown with repeat and delay

查看:43
本文介绍了带有重复和延迟的普通 JS 倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建倒计时脚本时一直遇到几个问题

I keep running into several issues when creating a countdown script

  1. 运行不流畅
  2. 难以重复(关闭)
  3. 难以延迟开始和延迟重复(结束)

有人可以帮我修复这段代码,它在我看来应该有效,但没有

Can someone please help me FIX this code which should work in my opinion but doesn't

我需要的处理是

一个.计数器开始延迟页面加载后的秒数,
湾当计数器达到0时,在延迟秒后重新开始倒计时

a. counter starts delay number of seconds after the page loads,
b. when counter reaches 0, the countdown RE-starts after delay number of seconds

这是我的小提琴

问题:

  1. 当它开始时,计数器似乎在倒计时之前多等一秒钟
  2. 它不会暂停
  3. 在计数器继续后开始重复

.

// more accurate timer - https://gist.github.com/1185904
function interval(duration, fn){
  this.baseline = undefined

  this.run = function(){
    if(this.baseline === undefined){
      this.baseline = new Date().getTime()
    }
    fn()
    var end = new Date().getTime()
    this.baseline += duration

    var nextTick = duration - (end - this.baseline)
    if(nextTick<0){
      nextTick = 0
    }
    (function(i){
        i.timer = setTimeout(function(){
        i.run(end)
      }, nextTick)
    }(this))
  }

  this.stop = function(){
   clearTimeout(this.timer)
  }
}
window.onload=function() {
  var cnt1 = 10;
  var delay1 = 5;
  var timer1 = new interval(1000, function(){
    document.getElementById('out1').innerHTML=cnt1--
    if (cnt1 <= 0) { // trying to reset
      timer1.stop(); // does not work
      cnt1 = 10;
      setTimeout(function() { timer1.run()},delay1*1000)
    }
  })
  setTimeout(function() { timer1.run()},delay1*1000)
}  

推荐答案

Object Exposing start([delay]) and stop().

Object exposing start([delay]) and stop().

http://jsfiddle.net/RVBDQ/3/

function interval(duration, fn, delay){
    this.timer = null;
    this.duration = duration;
    this.fn = fn;

    this.start(delay);
}
interval.prototype.start = function(delay){
    if (this.timer) {return;}
    var self=this;
    this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
    var self = this,
        nextTick = called ? this.duration - (new Date - called) : 0;

    this.timer = setTimeout(function(){
        self.fn();
        self.run(new Date);
    }, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
    clearTimeout(this.timer);
    this.timer = null;
};

window.onload = function() {
    var cnt1 = 10;
    var delay1 = 5;
    window.timer1 = new interval(1000, function(){
        document.getElementById('out1').innerHTML=cnt1;
        cnt1 = cnt1 === 1 ? 10 : cnt1-1;
    }, delay1*1000);
};

这篇关于带有重复和延迟的普通 JS 倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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