JavaScript Object Lifecycle

I have a Javascript class as shown 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 the init function, the loop starts and I get the text in the console every 1 second:

var ins = new MYCLASS();
ins.init();

Why, when I set the instance to null, the thread does not stop? or at any time when I create a new instance and assign it to the name of the previous instance, it increases the number of calls.

in my production code, I don't have an infinite loop, but I have some business logic. Do I need to worry about performance when creating a new instance?

+4
source share
2 answers

setTimeout, , . , timeOutID. , - - setTimeout, .

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);
    }
}
+4

.

, , , , , - .

. . javascript, ? "

, setTimeout , , null.

" ( kangax) :

, , ...; ; , ..

, .

... Variable ... . .

, .

, , .clearTimeout().

+2

Source: https://habr.com/ru/post/1599300/


All Articles