Benjamin753
Benjamin753

Reputation: 115

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?

Upvotes: 4

Views: 20217

Answers (4)

guest271314
guest271314

Reputation: 1

Try utilizing .data() , .queue() , animate() , .promise() ; to stop "countdown" can call $(element).clearQueue("countdown")

var counter = function counter(el) {
   return $(el || window).data({
    "start": {
      "count": 0
    },
    "stop": {
      "count": 1
    },
    "countdown": $.map(Array(90), function(val, key) {
                   return key
                 }).reverse(),
    "res": null
  })
  .queue("countdown", $.map($(this).data("countdown")
    , function(now, index) {
      return function(next) {
        var el = $(this);
        $($(this).data("start"))
        .animate($(this).data("stop"), 1000, function() {
          el.data("res", now)
          $("pre").text(el.data("res"));
          next()
        });
      }
    })
  )
  .promise("countdown")
  .then(function() {
    $("pre").text($(this).data("res"))
    .prevAll("span").text("countdown complete, count:");
  });
  };
  $("button").on("click", function() {
    if ($(this).is("#start")) {  
       counter();
       $("pre").text(90).prev("span").html("");
       $(window).dequeue("countdown");
    }
    else {
       $(window).clearQueue("countdown").promise("countdown")       
      .then(function() {
         $("pre").prevAll("span").html(function(_, html) {
         return html.replace("complete", "stopped")
       });
       })       
    }
  });
pre {
  font-size:36px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button id="start">start</button><button id="stop">stop</button>
<br />
<span></span>
<br />
<pre>90</pre>

Upvotes: 0

user1839730
user1839730

Reputation:

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

Upvotes: 4

Oriol
Oriol

Reputation: 288050

setInterval keeps calling your function at each second (since you use 1000).

So setInterval expects a function as its first argument, which is the function which will be called periodically. But instead of passing settime, you pass its returned value. That won't work, unless settime returns a function.

Instead, try

setInterval(settime, 1e3);

Upvotes: 0

Antonio Laguna
Antonio Laguna

Reputation: 9282

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

Upvotes: 5

Related Questions