M4RKYU.SYSEdition 2027
Skip to content
LOCEN/Ontario · CA/▸logs · in depth analysis of javascript memory model and lifecycle 2o55StandbyOK/--:--:--EST
M4M4RK_YUportfolio
  • BuildBuild
    BuildOverview
    • WorkSelected case studies and write-ups
    • GamesPlayable prototypes and game-dev logs
  • GalleryGallery
    GalleryOverview
    • PhotosPhoto collections and visual experiments
    • ShopPrints, posters, and one-off objects
  • WritingWriting
    WritingOverview
    • BlogLong-form devlogs and field notes
    • NotesShort observations, links, snippets
  • ResourcesResources
    ResourcesOverview
    • Tools38 in-browser developer utilities
    • LinksDaily-use dev and design bookmarks
  • AboutAbout
  • ContactContact
中文

syndicated · dev.to / @markyu

JavaScript Memory Leaks Usually Start With One Reference

A practical JavaScript memory guide covering stack, heap, garbage collection, closures, event listeners, timers, and leak debugging.

Published
May 22 '24
·
Reading time
2 min read
·
Reactions
6
javascriptperformancewebdevdebugging
View on dev.to

On this page

  • Stack vs Heap
  • The Leak Pattern
  • Event Listener Leak
  • Timer Leak
  • Closure Surprise
  • Debugging Checklist
  • Why This Still Matters in 2026
  • Final Thought

Most JavaScript memory leaks I have debugged were not dramatic.

They were one forgotten event listener, one timer that never stopped, or one closure holding a reference longer than expected.

The browser cannot collect memory if your code still points at it.

That is the whole game.

Stack vs Heap

The simplified model:

stack -> function calls, local primitives, references
heap  -> objects, arrays, functions, DOM nodes

Example:

function createUser() {
  const name = "Mark";
  const user = { name, role: "admin" };
  return user;
}

name is simple. user is an object on the heap, and the variable holds a reference to it.

When no live reference can reach that object, garbage collection can reclaim it.

The Leak Pattern

const cache = [];

function rememberUser(user) {
  cache.push(user);
}

If cache grows forever, those users stay reachable forever.

Visual map:

global cache -> user object -> nested profile -> big data

The garbage collector is not failing. Your references are doing exactly what you asked.

Event Listener Leak

This is common in UI code:

function mount() {
  window.addEventListener("resize", handleResize);
}

If you mount/unmount repeatedly and never remove the listener, old handlers stay alive.

Better:

function mount() {
  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize);
  };
}

React version:

useEffect(() => {
  window.addEventListener("resize", handleResize);
  return () => window.removeEventListener("resize", handleResize);
}, []);

Timer Leak

setInterval(() => {
  refreshDashboard();
}, 5000);

If the page or component is gone but the interval is still running, you have a leak or at least wasted work.

const intervalId = setInterval(refreshDashboard, 5000);
clearInterval(intervalId);

In React:

useEffect(() => {
  const id = setInterval(refreshDashboard, 5000);
  return () => clearInterval(id);
}, []);

Closure Surprise

Closures are useful, but they can keep data alive.

function createHandler(bigPayload) {
  return function onClick() {
    console.log(bigPayload.id);
  };
}

If onClick is stored somewhere long-lived, bigPayload stays alive too.

That is not a bug in closures. It is how closures work.

Debugging Checklist

In Chrome DevTools:

  1. Open Memory panel.
  2. Take a heap snapshot.
  3. Interact with the page.
  4. Force garbage collection if appropriate.
  5. Take another snapshot.
  6. Compare retained objects.

Look for:

  • detached DOM nodes
  • growing arrays/maps
  • duplicate listeners
  • long-lived closures
  • cached API responses with no eviction

Why This Still Matters in 2026

Modern frontends are heavier now: dashboards, AI chat UIs, long-context document tools, canvas apps, and multimodal assistants can all keep large objects around.

If your app stores every token, message, image preview, and intermediate state forever, the browser will eventually punish you.

Final Thought

JavaScript memory management is automatic, not magical.

The garbage collector cleans unreachable objects. Your job is to stop accidentally keeping everything reachable.

What was the weirdest memory leak you have debugged in JavaScript?

Related reading

Next.js Images Without CLS: My LQIP Blur-Up Setup

A practical Next.js image optimization guide for zero CLS layouts, blur placeholders, dimensions, remote images, and production image hygiene.

nextjs

Frontend Linear Data Structures Deep Dive: Arrays, Stacks, Queues, and Linked Lists

The Big Picture Before diving into stacks, queues, and linked lists, it helps to know...

computerscience

JS Sorting Algorithms Every Developer Should Know

You call .sort() every day without thinking about it. But the sorting algorithm your language's...

algorithms

originally published

This post first ran on dev.to. Comments and reactions live there.

Continue on dev.to
PreviousCSS Heart Animation: Small Demo, Real Animation LessonsA cleaner CSS heart animation tutorial focused on transform, pseudo-elements, keyframes, and the small mistakes that break simple UI animations.
Back to all posts
NextJava throw vs throws: The Exception Bug They RevealA practical Java exception handling guide explaining throw, throws, checked exceptions, runtime exceptions, and API boundary decisions.
Back to archive
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
Crafted since 2024
ZhenXiao Mark YuZhenXiao Mark Yu
get in touch

Saw something here?Tell me about it.

It's a portfolio, not a service · but I read every note — drop a line if anything here resonated, or just to say hi.

Start a conversation
open channel

say hi anytime · 2026

--:--:--ESTOntario, Canada
  • Email
  • GitHub
  • dev.to
  • LinkedIn
  • Twitter / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat

Newsletter

Get the occasional dispatch

Notes and logs from m4rkyu.com — short, dated, no noise. Unsubscribe anytime.

Work

Production builds, games, and visual archives.

  • Projects
  • Games
  • Archive
  • Logs

Resources

Daily-use tools and a personal link library.

  • Search
  • Latest
  • Tools
  • Links
  • Notes
  • Topics
  • Shop
RSSJSON feed

Studio

Background, contact, and channels for collaboration.

  • About
  • Contact
  • Changelog
  • Colophon
  • Resumepending

Socials

Find me on the usual feeds.

  • GitHub
  • dev.to
  • LinkedIn
  • Twitter / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
  • Email
© 2026 ZhenXiao Mark Yumarkyu0615@gmail.com
  • Email
  • GitHub
  • dev.to
  • LinkedIn
  • Twitter / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
PrivacyTermsBuilt with Next.js 16 · React 19 · Tailwind 4