Skip to content Skip to sidebar Skip to footer

Javascript Timer To Use Multiple Times In A Page

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 ='t

Solution 1:

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

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


functionstopTimer() {
  clearInterval(intervalLoop) // Also available here!
})

Solution 2:

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

Here 1000 means timer 1 sec

Solution 3:

I think something like this could be helpful:

Timer object declaration

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

 	returnthis;
};

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 selectorsdocument.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/

Post a Comment for "Javascript Timer To Use Multiple Times In A Page"