Make a timer using setInterval()

13,718

Solution 1

function timer(seconds, cb) {
  var remaningTime = seconds;
  window.setTimeout(function() {
    cb();
    console.log(remaningTime);
    if (remaningTime > 0) {
      timer(remaningTime - 1, cb); 
    }
  }, 1000);
}

var callback = function() {
  console.log('callback');
};

timer(90, callback);

Caution in using setInterval, may not work as you expect http://bonsaiden.github.io/JavaScript-Garden/#other.timeouts

Solution 2

Something like this should do the trick:

var count = 90;
var interval = setInterval(function(){
  setTime();
  if (count === 0){
    clearInterval(interval); // Stopping the counter when reaching 0.
  }
}, 1000);

I don't have the code you need but I'm sure you'll need to update the count at some point on your page.

You can cancel an interval with clearInterval which needs the ID of the interval that's created when you call setInterval

Share:
13,718
Benjamin753
Author by

Benjamin753

Updated on June 24, 2022

Comments

  • Benjamin753
    Benjamin753 almost 2 years

    I'm trying to make a timer in javascirpt and jQuery using the setInterval function. The timer should count down from 90 to zero (seconds).

    The code that I'm using for this:

    setInterval(settime(), 1000);
    

    in this settime() sets the var time (started on 90) -1, this action has to happen once every second. My problem is that I don't get how to let this action happen 90 times; I tried using a for loop but then the counter counts from 90 to 0 in 1 second.

    Does anyone knows a better alternative?