# JavaScript memory leak in Vanilla JS

> How to fix javascript memory leak in Vanilla JS — with the exact fix and copy-paste code.

_Category: Performance · Detector `memory-leak` · Severity: error_

A memory leak means the heap grows every time you navigate or interact and never comes back down, until long sessions jank, stutter, and eventually crash the tab. It is one of the hardest bugs to catch in review because it only shows up over time — the happy-path click looks fine. AI-generated effects and subscriptions are a frequent source: the setup is written, the cleanup is forgotten.

## The fix for Vanilla JS

Keep a reference to every listener/timer you add and release them when the view is destroyed. `AbortController` makes multi-listener cleanup a one-liner.

```js
const ac = new AbortController()
window.addEventListener('resize', onResize, { signal: ac.signal })
document.addEventListener('scroll', onScroll, { signal: ac.signal })
// teardown removes both at once:
ac.abort()
```

### Steps

1. Audit every effect/lifecycle hook that adds a listener, timer, or subscription
2. Return or register a cleanup that removes exactly what was added
3. Bound caches and growing arrays with an eviction policy (e.g. LRU or max size)

## How VibeCheck detects it

The `memory-leak` detector flags this live in the browser and reports it to the widget's Problems list — and to your coding agent over MCP.

- **Issue string:** `Potential memory leak (27% growth)`
- **Threshold:** > 10% heap growth over 30s without GC recovery (warning), > 25% (error)

## FAQ

### How do I confirm it is really a leak and not normal growth?

Take heap snapshots in DevTools Memory before and after repeating an action (e.g. navigate away and back a few times). If retained size keeps climbing and never drops after GC, it’s a leak. VibeCheck watches for exactly this: sustained growth with no recovery.

### React Strict Mode runs my effect twice — is that a leak?

No, that is intentional in development to surface missing cleanup. If your cleanup is correct and idempotent, the double-invoke is harmless and doesn’t happen in production.

### What are detached DOM nodes?

Nodes removed from the document but still referenced by JavaScript (a closure, a cached array, an event handler). They can’t be garbage-collected. Drop the reference when you remove the node.

See the general, framework-agnostic fix: https://vibecheck.wcgw.fun/fix/memory-leak.md

---

Fix guide from VibeCheck — https://vibecheck.wcgw.fun/fix/memory-leak. Full site index for LLMs: https://vibecheck.wcgw.fun/llms.txt
