Alexandre Goncalves Alexandre Goncalves - 6 months ago 35
Javascript Question

JavaScript recursive setTimeout

I defined this class in JavaScript:

function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(this.getstatus, 1000);
});
}
};
}


Once getstatus is called, it should start calling itself with setTimout, but it doesn't! It only works one time.

If I use a function without a class, it works!

Please help me out.

Thanks!

Answer

The problem is when getStatus is invoked by the timer, this inside the method does not refer to the object, you can pass a custom value for this using bind(). Also note that in the ajax callback this refers to the ajax settings object.

function Signal(lbl, ho, tag) {
    this.lbl = lbl;
    this.ho = ho;
    this.tag = tag;
    this.getstatus = function () {
        if (this.ho) {
            var signal = this;
            $.get('/get.cgi?' + this.tag + '=?0', function (data) {
                console.log(data);
                setTimeout(signal.getstatus.bind(signal), 1000);
            });
        }
    };
}