简体   繁体   中英

setTimeout with self executing function

I have an object and I want to write a self executing function within it. I have something like this:

var testObject= (function () {
function testObject() {
    this.counter = 0;
}

testObject.prototype.Cycle = function () {
    try {
        console.log("tick, ID: " + this.counter++);

        setTimeout(this.Cycle, 2000);
    } catch (ex) {
        console.log(ex);
    }
};

return testObject;
})();

And it works only once. Because at the first run it gives tick, ID: 0 and at the second time it gives tick, ID: undefined . What is the best way to achieve self executing function?

The problem you have is that this , in the callback, is window .

A solution :

testObject.prototype.Cycle = function () {
    try {
        console.log("tick, ID: " + this.counter++);
        setTimeout(this.Cycle.bind(this), 2000);
    } catch (ex) {
        console.log(ex);
    }
};

But you don't need all this code. You may simply do :

(function cycle(i){
    console.log("tick, ID: " + i);
    setTimeout(cycle, 2000, i+1);
})(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM