Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - garbage collector timers?

Any idea on garbage collector timer in javascript? Suppose i run below script, will function and associated scope chained variable will go for garbage collection exactly after 100ms? Or some margin?

I read one thread about garbage collection in stackoverflow, still i have this question. Below are my questions?

  1. Does any SYSTEM TIMER run for garbage collection task?
  2. If no, is it EVENT based?, means if reference is no more present, garbage collector will reclaim memory INSTANTLY.

    function call_me() {
    //calculate elapsed_time - code not given
    
               if(elapsed_time <100)
               {
                setTimeout(call_me,25);
               }
              else{
               final_call();
              }
    }
    
    call_me();
    
like image 585
P K Avatar asked May 23 '26 09:05

P K


2 Answers

Every user agent implements garbage collection differently. All user agents use the mark-and-sweep method on a periodic repetition, so there is no "instantly" about it; it will happen when it happens.

Each agent has different thresholds and mechanisms to determine when the GC does a pass. It isn't necessarily event-driven (purhaps you might say it is benchmark-driven, event-initiated), and certainly not based on a timer.

A function that passes out of scope is instantly eligible for garbage collection, but there's really no telling when it would happen.

This is really something that, from the developer perspective, you are not intended to think about. There isn't any way to stop or start GC, or any indication that it happened at all. Check out about:memory in Firefox for some interesting trivia (and there's a couple of dubious buttons down there to "control" the GC). That's about all you're going to get as far as it goes under the hood, and that data isn't available to scripts.

like image 152
Chris Baker Avatar answered May 25 '26 21:05

Chris Baker


The garbage collector is non-deterministic.
Garbage will be collected some time after it becomes garbage.

A closure object passed to setTimeout will become garbage after it executes.

Anything beyond that is implementation-specific.

like image 45
SLaks Avatar answered May 25 '26 22:05

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!