Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a timer using setInterval()

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?

like image 964
Benjamin753 Avatar asked Mar 15 '23 23:03

Benjamin753


1 Answers

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

like image 62
Antonio Laguna Avatar answered Mar 23 '23 13:03

Antonio Laguna