liveBook · Manning

Disconnectedcallback

As explained in Web Components in Action

disconnectedCallback is a custom-element lifecycle callback invoked when an element is disconnected from a document DOM.

disconnectedCallback is a custom-element lifecycle callback that fires when an element is removed from the document DOM. Use it as the component’s cleanup point: stop work that no longer belongs to a live element and release references that could keep other objects reachable. section 4.3

A practical cleanup sequence is:

  • Store handles for timers or other ongoing work when connectedCallback starts them. section 4.3
  • Cancel that work in disconnectedCallback, such as clearing an interval that would otherwise continue querying or updating after removal. section 4.3
  • Reset or null variables that link to other objects when those references are no longer needed, giving garbage collection an opportunity to reclaim memory. section 4.3
  • Treat cleanup as an option only when the element is genuinely never removed; changing application scope can make previously permanent components removable. section 4.3

Stop a repeating timer

class CleanupComponent extends HTMLElement { connectedCallback() { this.counter = 100; this.timer = setInterval(() => this.update(), 1000); } update() { this.innerHTML = this.counter; this.counter--; } disconnectedCallback() { clearInterval(this.timer); } } The handle saved as this.timer lets disconnectedCallback cancel the interval when the element leaves the DOM. section 4.3

Listing 4.7. Using disconnectedCallback to clean up a timer
class CleanupComponent extends HTMLElement {
   connectedCallback() {
       this.counter = 100;
       this.timer = setInterval( () => this.update(), 1000);
   }

   update() {
       this.innerHTML = this.counter;
       this.counter --;
       console.log(this.counter);
   }

   disconnectedCallback() {
       clearInterval(this.timer);        #1
   }
}

Browse the complete timer example showing connectedCallback, update, and disconnectedCallback working together. section 4.3

How Web Components in Action covers it

How deep it goes
Explains callback timing, timer cancellation, references, and garbage collection, but does not detail garbage-collector internals.
Examples
Uses a countdown component that continues running after removal until disconnectedCallback clears its interval.
What it assumes
Assumes familiarity with custom elements, the DOM, connectedCallback, and JavaScript timers.
What you can do after
Operate/configure custom elements by cancelling timers and resetting references when components leave the DOM.
How it connects
Connects custom elements with connectedCallback, garbage collection, timers, and game-engine lifecycle methods.

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.