Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object lifecycle

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?

like image 606
Ahmad Mousavi Avatar asked Jul 23 '15 12:07

Ahmad Mousavi


1 Answers

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);
    }
}
like image 122
XAMPPRocky Avatar answered Oct 05 '22 12:10

XAMPPRocky