Question

The setInterval function keeps running even though the object is nullified, should I change the setInterval var to null first or should I do something else? Also, will the GC remove the object even if the setInterval is still running?

Test = function(){
    function start(){
        // setTimout for controllable FPS
        var loop = setInterval(function(){
            console.log("TEST");
        }, 1000);
    }

    start();
};


var test = new Test();

setTimeout(function(){
    console.log("DIE!!");
    test = null;
}, 2000);

JsFiddle

Was it helpful?

Solution

the value returned by setInterval is just a number that used to identify the reference to the interval. you can't just null it - you need to call window.clearInterval on the reference.

there's a few other things that don't make sense in the code you posted. for example, you're declaring a function in a function then just calling it once. i think this is probably closer to what you want:

var Test = function(){
  this.start();
}
Test.prototype = {
  loop : null,
  start : function(){
    this.loop = window.setInterval(function(){
      console.log('TEST');
    }, 1000);
  },
  stop : function(){
    window.clearInterval(this.loop);
  }
}

var test = new Test();
window.setTimeout(function(){
  test.stop();
}, 5000);

That'll run the interval 5 times.

FWIW, the GC isn't really involved here. As long as there's a reference to any variable, it won't be collected.

HTH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top