当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js实现网页同时进行多个倒计时功能

js实现网页同时进行多个倒计时功能

2019年03月17日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了js实现网页同时进行多个倒计时的具体代码,供大家参考,具体内容如下

创建一个时间类timer.

每个商品的倒计时生成一个实例:var time = new timer();

/**
*startime 应该是毫秒数
*/
 
var alarm = function (startime, endtime, countfunc, endfunc) {
    this.time = math.floor((endtime - startime) / 1000); //时间
    this.countfunc = countfunc; //计时函数
    this.endfunc = endfunc; //结束函数
    this.flag = 't' + date.parse(new date()); //
  };
alarm.prototype.start = function () {
  var self = this;
 
  self.flag = setinterval(function () {
    if (self.time < 0) {
      clearinterval(self.flag);
      self.endfunc();
      console.log('计时结束');
    } else {
      var minute, hour, day, second;
      day = math.floor(self.time / 60 / 60 / 24) < 10 ? '0' + math.floor(self.time / 60 / 60 / 24) : math.floor(self.time / 60 / 60 / 24);
      hour = math.floor(self.time / 60 / 60 % 24) < 10 ? '0' + math.floor(self.time / 60 / 60 % 24) : math.floor(self.time / 60 / 60 % 24);
      minute = math.floor(self.time / 60 % 60) < 10 ? '0' + math.floor(self.time / 60 % 60) : math.floor(self.time / 60 % 60);
      second = math.floor(self.time % 60) < 10 ? '0' + math.floor(self.time % 60) : math.floor(self.time % 60);
      //倒计时执行函数
      self.countfunc(second, minute, hour, day);
      self.time--;
    }
  }, 1000);
}

如果调用:

var time1 = new alarm(startime, endtime, countfunc, endfunc);
time1.start();
 
var time2 = new alarm(startime, endtime, countfunc, endfunc);
time2.start();
...

调用示例:

var counttime = function () {
  var eles = $('.count_time'),
    len = eles.length;
  for (; len > 0; len--) {
    var ele = eles.eq(len - 1);
    (function (ele) {
      starttime = new date(ele.attr('data-start-time')).gettime(),
          endtime = new date(ele.attr('data-end-time')).gettime(),
          alarm = new alarm(starttime, endtime, function (second, minute, hour, day) { //计时钟
            ele.text(hour + ':' + minute + ':' + second);
          }, function () { //倒计时结束
            ele.text('00:00:00');
            window.location.reload();
          });
      alarm.start();
    })(ele);
  }
};
counttime();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网