I have the following code for my simple stopwatch, which only counts the number of seconds with no formatting whatsoever:
function countDown(from, interval, callback) {
interval = interval || 1000;
var current = 0;
var onCount = function() {
current++;
if (current <= from) {
callback(current, from);
setInterval(onCount, interval);
}
}
onCount();
}
This is called with an onclick, with the following code:
countDown(600, 1000, function(current, from) {
time_out.innerHTML = current;
});
Putting in a console.log(current), I can see two problems. First, though it does go through every number, it seems to get faster and faster, by powers of two. In the output div, the first tick will be 1, the second will be 2, the third will be 4, the fourth will be 8, and so on. Furthermore, it does not actually stop counting when it hits 600, even though it stops updating the div. What did I do wrong here?
You use
setIntervalwhich will call the callback at a set interval every time the function is called, resulting many many calls tocountDown()Maybe you wanted to use the
setTimeoutfunction instead, which will only call the function once after the delay.