suchcodemuchwow
suchcodemuchwow

Reputation: 1046

Settimeout inside of object method

Given code snippet of code does not stop even though I'm using setTimeout in it.

var myObj = {
    myFunc: function () {
        var self = this;
        var timer = setTimeout(function () { 
            console.log('Timeout called'); 
            self.myFunc();
        }, 100);
    }
};
myObj.myFunc();
myObj = null;

Upvotes: 0

Views: 118

Answers (1)

Prasun
Prasun

Reputation: 5023

Inside the setTimeout callback, the given code recursively calling myFunc (self.myFunc()), that's why it is going forever.

Upvotes: 2

Related Questions