在页面中多次使用的 Javascript 计时器 [英] Javascript timer to use multiple times in a page

查看:39
本文介绍了在页面中多次使用的 Javascript 计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完美运行的 Javascript 倒数计时器.唯一的问题是我只能在一页中使用它一次.我想多次使用它.

I have this Javascript count down timer that works perfectly. Only problem is i can use it for only one time in one page. I want to use it multiple times.

我认为脚本使用 id ="timer" 这就是为什么我不能多次使用它.

I think script use id ="timer" that is why i am not able to use it multiple times.

下面是JS代码:

<script>
var startTime = 60; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
var space = '       ';

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var intervalLoop = 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 = "00" + space + minutes + space + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

window.onload = function() {
  var now = new Date();
  var hrs = now.getHours();
  var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
    display = document.querySelector("#timer");

  startTimer(setMinutes, display);
};
</script>

推荐答案

我认为这样的事情可能会有所帮助:

I think something like this could be helpful:

定时器对象声明

var timerObject = function(){
	this.startTime = 60; //in Minutes
	this.doneClass = "done"; //optional styling applied to text when timer is done
	this.space = '       ';

 	return this;
};

timerObject.prototype.startTimer = function(duration, display) {
  var me = this, 
    timer = duration,
    minutes, seconds;
  var intervalLoop = 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 = "00" + me.space + minutes + me.space + seconds;
    if (--timer < 0) {
      // not sure about this part, because of selectors
      document.querySelector("#timer").classList.add(me.doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

像使用它一样

var t1 = new timerObject();
var t2 = new timerObject();
t1.startTimer(a,b);
t2.startTimer(a,b);

JS 小提琴示例:

UPD1 注释部分,以便可以停止计时器

https://jsfiddle.net/9fjwsath/1/

这篇关于在页面中多次使用的 Javascript 计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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