I have a Javascript class like below:
var MYCLASS = function(elem, data, op) {
    var options = {};
    var loopForEver = function() {
        console.log('I cant stop me');
        setTimeout(function() {
            loopForEver();
        }, 1000);
    }
    this.init = function() {
        loopForEver();
    }
}
when I instantiate the class and call init function, then the loop starts and I get the text in my console every 1 second :
var ins = new MYCLASS();
ins.init();
Why when I set the instance to null, the thread does not stop? or any time I create a new instance and assign it to the previous instance name, it increases the calls.
in my production code, I do not have infinite loop, but I do have some business logic. do I need to be worried about performance when I create a new instance?
When you call setTimeout it is not bound by the function that called it. You need to add a property to object called something like timeOutID. As long as the function is still required being used by something like setTimeout it will remain in scope.
var MYCLASS = function(elem, data, op) {
    var options = {};
    var timeOutID = null;
    var loopForEver = function() {
        console.log('I cant stop me');
        timeOutID = setTimeout(function() {
            loopForEver();
        }, 1000);
    }
    this.init = function() {
        loopForEver();
    }
    this.stop = function () {
      clearTimeout(timeOutID);
    }
}
                        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