Reputation: 2020
I've got this code:
var delta = data[1];
var expire = new Date();
expire.setSeconds(expire.getSeconds() + delta);
var tick = function() {
var now = new Date();
if (now > expire) {
return false;
}
return true;
};
var cancel = setInterval(function() {
if (!tick()) {
clearInterval(cancel);
}
}, 1000);
data[1] is just the amount in seconds it needs to countdown.
Current it just resets when it is over, but I want to display the seconds remaining at every tick in console, how could I go about doing this?
Upvotes: 0
Views: 33
Reputation: 288260
You can try returning the remaining time instead of true
:
var remaining = 5e3;
var start = new Date();
var tick = function() {
var diff = remaining - new Date() + +start;
return diff < 0 ? false : diff;
};
var cancel = setInterval(function() {
var diff = tick();
if (diff === false) clearInterval(cancel);
else console.log(diff);
}, 1000);
Upvotes: 0
Reputation: 8523
Rather than rely on dates, which is definitely a possibility, if you're trying to keep this as simple as your specifications, I would just have a countdown variable.
var currentTime = delta;
var timer = setInterval(function () {
if (currentTime == 0) {
clearInterval(timer);
}
else {
currentTime--;
console.log(currentTime);
}
}, 1000);
Upvotes: 1