Javascript计时器在页面中多次使用

时间:2017-06-06 11:42:40

标签: javascript timer

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

我认为脚本使用id ="timer"这就是为什么我无法多次使用它。

以下是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>

3 个答案:

答案 0 :(得分:0)

只需在intervalLoop函数之外声明startTimer,它就可以在全球范围内使用。

var intervalLoop = null

function startTimer(duration, display) {
  intervalLoop = setInterval(function() { .... }
})


function stopTimer() {
  clearInterval(intervalLoop) // Also available here!
})

答案 1 :(得分:0)

window.setInterval(function(){ Your function }, 1000);

此处1000表示timer 1 sec

答案 2 :(得分:0)

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

计时器对象声明

&#13;
&#13;
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);
}
&#13;
&#13;
&#13;

一样使用它
var t1 = new timerObject();
var t2 = new timerObject();
t1.startTimer(a,b);
t2.startTimer(a,b);

JS小提琴示例:

UPD1注释了部分,因此可以停止计时器

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