To understand how JavaScript recovers memory, you need to understand context
first.
One of the many reasons that JAvaScript has moved from using var
to using const
and let
is that these help you and the JIT understand when a variable is no longer needed by constraining its context more granularly.
In generaly, a variable that uses const
or let
or is a parameter on a function (though note the caveat below) will be released once the surrounding execution context is completed. In a simple function or an if block, this would be at the end of the function/block.
In your example, things are more complex since your function is actually an event listener. I think that will retain the function on memory unless you removed it from the list. But any variables in the function would be created and destroyed on each run. Though I'm not entirely sure that is complete because the optimiser will also have kicked in when you run node.js so maybe things are a bit more complex.
But the implication of your code is that interval
is created in some higher level of context. All that contains is a reference to the running interval function. I think that once you've cleared the interval, that reference is likely set to undefined
, that is easy to test of course. The point being that I don't think that trying to set interval
to null will recover much if anything.
But trying to set this
to null is a really bad idea. In the context of the function, this
is the function itself so you are trying to destroy the function from within. Not sure that the result will be consistent but it is probably a "bad thing" TM.
Once JavaScript has finished with variables, GC can later recover the space on the Heap.
The exception about parameters I mention are, of course, because JS passes by REFERENCE and so you do not get a copy unless the content is a base value (string, boolean, number, etc). So recovery of that is minimal given that it will only be a reference. Though a long string might be more impactful.
One thing that I do in uibuilder in the close (and by the way, I use node.close
rather than this.close
because it is too easy to end up with the wrong this
) is that I do remove the input listener.
So in my nodes, I use a function I always call nodeInputHandler
, in node.close
, I include: node.removeListener('input', nodeInputHandler)
to make sure that if the node restarts, I don't end up with two instances of the listener.
I also make sure that I close out and remove any websocket/socket.io instances and any ExpressJS middleware and routes that my node may have added.
Sorry, another update. Do make sure that you have not accidentally used a variable without declaring it. If you do that it will be attached to global
and so may not be released. Also, make sure that you always use 'use strict'
and use a good code editor such as VScode with ESLINT. JavaScript is not the easiest or most logical of languages and using an editor with good linting is a great way to avoid all many of issues.