Assume I have the following myFunction & setTimeout duo
function myFunction(){
var am_i_eaten = 'ffdfjdhsfhs';
setTimeout(function(){
console.log(am_i_eaten);
},3000);
}
myFunction();
Will the setTimeout keep the scope of myFunction alive (since it can still print am_i_eaten without problem), and prevent it from being garbage collected in my Node.JS environment? I believe the behavior to be somewhat different than the behavior in a browser?
Thanks!
What you have created is a function closure and the variables in that closure will not be garbage collected until after the setTimeout() callback runs.
You can conceptually think of the local variables to a function as individual items that are garbage collected only when no other code that can still be called can reach those variables. So, until after your setTimeout() callback runs, the variable am_i_eaten is still reachable and will not be garbage collected.
This works identically in the browser and in node.js (its literally the same V8 JS engine in Chrome and node.js).
setTimeout arbitrary data will be automatically collect by garbage collector once timeout operation done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With