Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a setTimeout keep a function from being garbage collected?

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!

like image 402
josh Avatar asked Nov 07 '25 17:11

josh


2 Answers

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).

like image 103
jfriend00 Avatar answered Nov 09 '25 08:11

jfriend00


setTimeout arbitrary data will be automatically collect by garbage collector once timeout operation done.

like image 26
bhagyashri patil Avatar answered Nov 09 '25 09:11

bhagyashri patil