Javascript timer to use multiple times in a page

非 Y 不嫁゛ 提交于 2021-01-28 05:20:17

问题


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.

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

Below is the JS code:

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

回答1:


Just declare intervalLoop outside of the startTimer function, it'll be available globally.

var intervalLoop = null

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


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



回答2:


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

Here 1000 means timer 1 sec




回答3:


I think something like this could be helpful:

Timer object declaration

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

Use it like

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

JS Fiddle example:

UPD1 commented part so the the timer could be stopped

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



来源:https://stackoverflow.com/questions/44389105/javascript-timer-to-use-multiple-times-in-a-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!