liveBook · Manning

Garbage collection

As explained in Web Components in Action

Garbage collection is automatic memory management that reclaims storage occupied by objects no longer reachable by a program.

Garbage collection automatically reclaims memory occupied by objects that a JavaScript engine can no longer reach. It cannot know which objects you no longer need merely by intent; it looks for missing references or links. section 4.3

Web Components make the practical risk visible. Removing an element from the DOM does not automatically stop its timer or server polling. Use disconnectedCallback to clear timers and reset or null variables that link to other objects, giving garbage collection a better opportunity to reclaim them. section 4.3

Stop work when the element leaves the DOM

Store the interval handle, then clear it during disconnection: connectedCallback() { this.timer = setInterval(() => this.update(), 1000); } disconnectedCallback() { clearInterval(this.timer); } Without the cleanup callback, the component can continue updating and querying after removeChild removes it. section 4.3

Figure 4.3. Memory references inside a Web Component

Trace which objects remain linked inside a Web Component and which references can become collectible. section 4.3

How Web Components in Action covers it

How deep it goes
Defines reachability and demonstrates timer cleanup, without detailing garbage-collector algorithms.
Examples
Uses a removed custom element with a repeating timer or server query and disconnectedCallback cleanup.
What it assumes
Assumes Web Component lifecycle and DOM-removal knowledge while contrasting JavaScript collection with C++ manual release.
What you can do after
Apply it via JavaScript by clearing component timers and resetting or nulling object links when elements leave the DOM.
How it connects
Ties garbage collection to Web Components, DOM removal, disconnectedCallback, timers, and memory references.

Also explained in

Compare how 9 books explain garbage collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.