{"success":true,"name":"clean-up-event-listeners-timers-and-observers-in-javascript","description":"JS code adds listeners, intervals, or observers in long-running pages.","category":"ai-brimind","path":"ai-brimind/clean-up-event-listeners-timers-and-observers-in-javascript/SKILL.md","file":"SKILL.md","content":"---\nname: clean-up-event-listeners-timers-and-observers-in-javascript\ndescription: \"JS code adds listeners, intervals, or observers in long-running pages.\"\n---\n\n# Clean Up Event Listeners, Timers, and Observers in JavaScript\n\n## When to use\nProject is JavaScript, and code registers addEventListener, setInterval, setTimeout loops, or observers — especially in views that get created and destroyed repeatedly or apps that stay open for hours.\n\n## Example request\nA view re-initializes and adds its listeners again → after 10 navigations, one click fires the handler 10 times — duplicate listener accumulation. setInterval started on a screen that gets closed → it keeps running forever against dead DOM — orphaned timer. App open all day slowly gets sluggish → hundreds of forgotten handlers and references pile up — memory leak from missing teardown.\n\n## Instructions\nAct like a developer who pairs every 'start' with a written 'stop' before running anything. Whenever code registers something ongoing (addEventListener, setInterval, requestAnimationFrame loops, MutationObserver, WebSocket): (1) at the moment you write the registration, also write its teardown — removeEventListener with the SAME function reference (anonymous inline functions cannot be removed; store the handler in a variable), clearInterval with the saved id, observer.disconnect(); (2) identify WHEN teardown runs — view close, navigation away, component destroy — and wire it there; if the codebase has no lifecycle hook for that, create one place that cleans up; (3) for repeatedly initialized views, guard against double registration: either tear down before re-init or check a flag. This matters most in long-running apps (TV apps, dashboards, single-page apps) where leaks compound over hours. Only proceed once every ongoing registration has a named owner of its cleanup, and verify by triggering the create/destroy cycle several times and confirming handlers fire exactly once.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1016\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}