Here is a fiddle.
I'm trying to create a countdown object that uses moment.js (a plugin that I prefer over using Date())
var Countdown = function(endDate) {
this.endMoment = moment(endDate);
this.updateCountdown = function() {
var currentMoment, thisDiff;
currentMoment = moment();
thisDiff = (this.endMoment).diff(currentMoment, "seconds");
if (thisDiff > 0)
console.log(thisDiff);
else {
clearInterval(this.interval);
console.log("over");
}
}
this.interval = setInterval(this.updateCountdown(), 1000);
}
I then create a instance of the countdown like so:
var countdown = new Countdown("January 1, 2014 00:00:00");
However the function only seems to run one time. Any ideas? Should I be using setTimeout() instead?
The setInterval() method is JavaScript is used to evaluate an expression at intervals. Here's the syntax: setInterval(function, interval_in_milliseconds, param1, param2, param3...) Here, interval_in_milliseconds sets the intervals in milliseconds, after the code will execute.
JavaScript setInterval() method. The setInterval() method in JavaScript is used to repeat a specified function at every given time-interval. It evaluates an expression or calls a function at given intervals. This method continues the calling of function until the window is closed or the clearInterval() method is called ...
setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .
In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.
You should pass a reference to function, not the result of its execution. Also, you need some additional "magic" to call a method this way.
var me = this;
this.interval = setInterval(function () {
me.updateCountdown();
}, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With