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
