0

I want to run an array of neural network trainers, it's running on an infinite loop like this:

Trainer.prototype.tick = function(){ // do the try something and record the score setTimeout(function(){ this.tick() },0); } 

So far it doing well but when I want to renew the training data and the neural networks, I will delete the trainer instance from my array and replace with a new instance. So the question is will it really delete the old instance and free up the memory?

1 Answer 1

2

Javascript is a garbage collected language. That means that it automatically removes objects from memory when no active, reachable code still has a reference to the object. So, if you remove the object from an array and no other variable or property in your code has a reference to that object, then the object will be eligible for garbage collection and the system will free the memory that it occupies.

While your setTimeout() is active, there is still a reference to your object so it can't be garbage collected until the setTimeout() fires. But, since you're using a timer value of 0, the timer will fire very soon and that particular reference to the object will be cleared.

But, your setTimeout() immediately tries to call this.tick(). If that call succeeded, it would set another setTimeout() so it will never stop and will never be garbage collected. You'd have to stop setting new timers for it to be garbage collected.

But, in the code you show, the value of this will not be pointing at your Trainer object so the call to this.tick() will fail and no new timer will be set and as soon as the setTimeout() runs and the this.tick() call fails, the object will be ready for garbage collection.

Sign up to request clarification or add additional context in comments.

4 Comments

Is that mean it will run the last circle then will be removed entirely?
@HankPhung - I don't know what "run the last circle" means.
ops sorry, I meant will it run 1 more loop then stop and removed?
@HankPhung - I didn't realize until just now that your setTimeout() was trying to call this.tick() which would set another setTimeout(). But, the call to this.tick() will fail with the code you show. Anyway, see more explanation I added to my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.