Advanced 12 min

Memory and event listener cleanup

Objects remain in memory while reachable code can still find them.

How it works

If a window listener remembers one view’s data, that data stays reachable for as long as the listener does. Register and remove listeners at matching points in the view’s lifetime. A quick symptom to look for is the same callback firing twice after a screen is reopened.

Walk through an example

A listener registered on window can keep a closure and its captured objects reachable. A long-lived page may accumulate these if returning to a view repeatedly registers more listeners.

What to watch for

Keep a reference to the callback or use an abort signal so leaving a view can remove its registered listeners.

Check your understanding

What should happen when the view closes?

See the example and explanation
Worked example
Given A view registers a resize callback each time it opens.
Answer Remove that view’s resize callback.

Window can outlive the view. Removing the listener prevents extra callbacks and releases objects kept alive only through that listener.

Open practice problem
Next lessonCoordinating multiple promises