Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Javascript Object Method with SetInterval()

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?

like image 972
dougmacklin Avatar asked Aug 15 '13 23:08

dougmacklin


People also ask

How do you call a method in setInterval?

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.

Does the setInterval () function work in JavaScript?

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 ...

How does the setInterval () function work in?

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() .

Why you should not use setInterval?

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.


1 Answers

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);
like image 177
kirilloid Avatar answered Oct 12 '22 23:10

kirilloid