Memory leaks and garbage collection
How JavaScript decides what to free — reachability, roots, mark-and-sweep and V8's generations — why web apps still leak through listeners, timers, detached nodes and caches, and how to find leaks with heap snapshots.
This topic starts at Junior level.
Reachability: what the garbage collector keeps
JavaScript-də free() yoxdur. Obyekt, massiv, sətir və closure yaradanda yaddaş ayrılır, onu geri qaytarmaq isə mühərrikin işidir. Onun qaydası sadədir: obyekt əlçatan qaldıqca — hansısa kökdən ona aparan istinad zənciri olduqca — saxlanılır, belə zəncir qalmayanda isə zibilə çevrilir.
Köklər collector-un həmişə "canlı" saydığı başlanğıc nöqtələridir:
- qlobal obyekt (
globalThis, brauzerdəwindow) və onun saxladığı hər şey; - hazırda olan funksiyaların lokal dəyişənləri və arqumentləri;
- host-un sənin əvəzinə saxladığı istinadlar: sənəddəki DOM node-ları, qeydə alınmış event listener-lər, gözləyən taymerlər və promise callback-ləri, açıq bağlantılar.
let user = { name: "Ada", avatar: new Uint8Array(1_000_000) };
const session = { user };
user = null;
session.user = null;user = null heç nəyi azad etmədi: o, yalnız bir yolu sildi, obyekt isə session.user vasitəsilə hələ də əlçatan idi. Yalnız ikinci mənimsətmədən sonra ona heç nə aparmır və collector onu təmizləyə bilər. delete obj.key də eyni cür işləyir: istinadı silir, yaddaşı dərhal boşaltmır. Collector-un nə vaxt işə düşəcəyinə mühərrik özü qərar verir, səhifənin kodu onu çağıra bilməz.
Dövri istinadlar problem deyil
Köhnə reference counting collector-ları dövrləri sızdırırdı: bir-birinə istinad edən iki obyektin sayğacı heç vaxt sıfıra düşmürdü. Müasir mühərriklər isə köklərdən başlayıb istinadları izləyir, ona görə də təcrid olunmuş dövr sadəcə əlçatmaz olur:
function link() {
const a = {};
const b = { a };
a.b = b;
}
link();link() qayıtdıqdan sonra a və b hələ də bir-birinə istinad edir, amma onlara heç nə aparmır, ona görə hər ikisi təmizlənə bilər. MDN qeyd edir ki, heç bir müasir JavaScript mühərriki artıq garbage collection üçün reference counting istifadə etmir. Yəni "dövri istinadlar sızma yaradır" məsləhəti adi JavaScript obyektləri üçün köhnəlib.
Əsas məqamlar
- Yaddaş obyekti "silməklə" yox, istinadları buraxmaqla azad olunur.
- Əlçatan "yenə istifadə olunacaq" demək deyil, "kökə bağlıdır" deməkdir. Bir daha toxunmayacağın obyekt də, uzunömürlü bir şey ona istinad edirsə, yaddaşda qalır.
- Məhz bu boşluq — əlçatandır, amma artıq lazım deyil — adlanır.
JavaScript has no free(). You allocate memory by creating objects, arrays, strings and closures, and the engine's reclaims it for you. Its rule is simple: an object is kept while it is reachable — while some chain of references leads to it from a root — and becomes garbage when no such chain is left.
Roots are the starting points the collector always treats as alive:
- the global object (
globalThis,windowin a browser) and everything it holds; - local variables and arguments of the functions currently on the ;
- references the host keeps on your behalf: DOM nodes in the document, registered event listeners, pending timers and promise callbacks, open connections.
let user = { name: "Ada", avatar: new Uint8Array(1_000_000) };
const session = { user };
user = null;
session.user = null;user = null did not free anything: it removed one path, and the object was still reachable through session.user. Only after the second assignment does nothing lead to it, and the collector may free it. delete obj.key works the same way — it removes a reference, it does not release memory on the spot. When the collector actually runs is the engine's decision; page code cannot trigger it.
Cycles are not a problem
Old reference-counting collectors leaked cycles: two objects pointing at each other never reached a count of zero. Modern engines trace from the roots instead, so an isolated cycle is simply unreachable:
function link() {
const a = {};
const b = { a };
a.b = b;
}
link();After link() returns, a and b still reference each other, but nothing reaches them, so both can be collected. MDN states that no modern JavaScript engine uses reference counting for garbage collection any more — "circular references leak" is outdated advice for plain JavaScript objects.
Key points
- Memory is freed by dropping references, never by "deleting" an object.
- Reachable means "connected to a root", not "will be used again". An object you will never touch is still kept if something long-lived points at it.
- That gap — reachable, but no longer needed — is exactly what a is.
What a leak is in a garbage-collected language
JavaScript-də proqramın artıq ehtiyac duymadığı, amma hələ də istinad etdiyi yaddaşdır: collector onu saxlamağa məcburdur. Burada collector səhv etmir — o sənin niyyətini görmür, yalnız əlçatanlığı görür.
Sızma səhifəni bir dəqiqəyə çökdürmür. O, yavaş-yavaş yığılır: istifadəçi hər dəfə dialoq açanda, single-page tətbiqdə görünüşü dəyişəndə və ya WebSocket mesajı alanda bir az daha yaddaş geridə qalır. Tipik əlamətlər:
- JS heap hər təkrarlanan əməliyyatla böyüyür və heç vaxt ilkin səviyyəsinə qayıtmır;
- uzun sessiyada tətbiq yavaşlayır: işarələnməli canlı obyekt çoxaldıqca üzərində GC işi də uzanır və tezləşir;
- yan təsirlər təkrarlanır: dublikat sorğular, iki dəfə işləyən handler — sızan kod çox vaxt hələ də işləyir;
- ən pis halda tab-ın yaddaşı bitir və brauzer onu bağlayır.
Hər böyümə sızma deyil. 50 MB data yükləyib onu göstərən səhifə çox yaddaş işlədir, amma sızdırmır. Sızma təkrarla bağlı böyümədir: eyni işi on dəfə görürsən, yaddaş da on pillə qalxır.
const seen = [];
export function onMessage(message) {
seen.push(message);
render(message);
}Modul səviyyəsindəki bu massiv səhifə yaşadıqca əlçatandır, ona görə də indiyədək gələn hər mesaj yaddaşda qalır. Qısa testdə heç nə görünmür, bir günlük axından sonra isə massiv yüz meqabaytlarla yaddaş tuta bilər.
Yaddaş və davranış
Real həyatda tez-tez rast gəlinən mənzərə: ekran serverə polling sorğuları göndərməyə başlayır və heç vaxt dayanmır. İstifadəçi onu hər açanda daha bir poller başlayır. Uzun sessiyadan sonra səhifə lazım olduğundan dəfələrlə çox sorğu göndərir, hər köhnə poller isə çoxdan silinmiş komponentin state-ini yaşadır. Bu mənzərə tipikdir: sızma həm yaddaşda, həm də davranışda özünü göstərir.
Verilməli sual
Hər uzunömürlü istinad üçün soruş: onu kim silir və nə vaxt? Cavab "heç kim"dirsə, sızma namizədi tapmısan. Mövzunun qalan hissəsi bu suala adətən hansı cavabların verildiyindən və onları necə yoxlamaqdan bəhs edir.
A in JavaScript is memory the program no longer needs but still references, so the collector has to keep it. The collector is not wrong: it cannot see your intent, only reachability.
Leaks rarely crash a page in a minute. They accumulate: each time the user opens a dialog, switches a view in a single-page app or receives a WebSocket message, a little more stays behind. Typical symptoms:
- the JS heap grows with every repetition of an action and never returns to its baseline;
- the app gets slower over a long session: more live objects to mark means longer and more frequent GC work on the ;
- side effects repeat: duplicate requests, a handler that runs twice — the leaked code is often still working;
- in the worst case the tab runs out of memory and the browser kills it.
Not every growth is a leak. A page that loads 50 MB of data and shows it uses a lot of memory, but it is not leaking. A leak is growth tied to repetition: do the same thing ten times and memory climbs ten steps.
const seen = [];
export function onMessage(message) {
seen.push(message);
render(message);
}This module-level array is reachable for the lifetime of the page, so every message ever received stays in memory. A short test shows nothing; after a day of streaming it can hold hundreds of megabytes.
Memory and behaviour
A common real-world shape: a screen starts polling the server and never stops. Every time the user opens it, one more poller starts. After a long session the page sends requests many times more often than it should, and each old poller keeps the state of a component that is long gone. That combination is typical: a leak shows up both as memory and as behaviour.
The question to ask
For every long-lived reference, ask: who removes it, and when? If the answer is "nobody", you have found a leak candidate. The rest of this topic is about the usual answers to that question and how to confirm them.
Common sources: listeners, timers and globals
Veb tətbiqlərdəki sızmaların çoxu eyni sxemlə yaranır: uzunömürlü bir şey (window, document, qlobal store, brauzerin taymer siyahısı) qısaömürlü bir şeyə (dialoq, komponent, sorğu) istinad edir və bu istinadı heç kim silmir.
Unudulmuş event listener-lər
function openSearchDialog() {
const results = new Array(10_000).fill(null);
function onKeyDown(event) {
if (event.key === "Escape") closeDialog(results);
}
document.addEventListener("keydown", onKeyDown);
}Hər çağırış yeni funksiya qeydə alır, document onların hamısını saxlayır, hər listener-in isə öz results massivini. Dialoqu on dəfə aç: on listener, on massiv və eyni anda işləyən on Escape handler-i. Listener-i dialoq bağlananda sil və bunu eyni funksiya referansı ilə et — removeEventListener-ə təzə yazılmış arrow funksiya ötürsən, heç nə silinməyəcək.
Özü silinib unudulmuş elementin listener-i isə sızma deyil: element də, onun listener-ləri də birlikdə əlçatmaz olur. Təhlükə funksionallıqdan uzun yaşayan hədəflərə bağlanmış listener-lərdədir.
Təmizlənməyən taymerlər
Brauzer setInterval callback-inə clearInterval çağırılana qədər, gözləyən setTimeout-a isə o işə düşənə qədər istinad edir. Özünü yenidən planlaşdıran setTimeout üzərində qurulmuş polling dövrü, zənciri kimsə qırmasa, əbədi yaşayır:
function startPolling(load) {
let timer;
let stopped = false;
const tick = async () => {
await load();
if (!stopped) timer = setTimeout(tick, 5000);
};
tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}stopped bayrağı vacibdir: dayandırma funksiyası load() hələ icra olunarkən çağırıla bilər və bayraq olmasa, növbəti taymer yenə də planlaşdırılacaq.
Təsadüfi qlobal dəyişənlər
Sloppy mode skriptlərində elan olunmamış ada dəyər mənimsətmək qlobal obyektdə xassə yaradır, bu xassə isə kökdür:
function cacheResponse(data) {
lastResponse = data;
}lastResponse artıq səhifə qədər yaşayır. ES modulları və strict mode kodu bunun əvəzinə ReferenceError atır — modullarla yazmağın daha bir səbəbi. Bilərəkdən yaradılmış qlobal dəyişənlər və modul səviyyəsindəki dəyişənlər də kökdür: onların saxladığı hər şey bütün sessiya boyu yaşayır.
Konsola yazılan obyektlər
DevTools açıq olanda console.log-a ötürülən obyektlər, sonradan açıb baxa biləsən deyə, saxlanıla bilər; heap snapshot-larda hətta konsolun saxladığı obyektlər üçün ayrıca filtr var. Bunu öz kodundakı sızma ilə qarışdırma və dövr içində böyük obyektləri log edən kodu production-a çıxarma.
Most leaks in web apps follow one pattern: something long-lived (the window, the document, a global store, the browser's timer list) holds a reference to something short-lived (a dialog, a component, a request), and nobody removes it.
Forgotten event listeners
function openSearchDialog() {
const results = new Array(10_000).fill(null);
function onKeyDown(event) {
if (event.key === "Escape") closeDialog(results);
}
document.addEventListener("keydown", onKeyDown);
}Each call registers a new function, the document keeps all of them, and each listener's keeps its own results. Open the dialog ten times: ten listeners, ten arrays, ten Escape handlers firing at once. Remove the listener when the dialog closes, using the same function reference — removeEventListener with a freshly written arrow function removes nothing.
A listener on an element that is itself removed and forgotten is not a leak: the element and its listeners become unreachable together. The danger is listeners on targets that outlive the feature.
Timers that are never cleared
The browser references a setInterval callback until clearInterval, and a pending setTimeout until it fires. A polling loop built from a setTimeout that re-schedules itself lives forever unless something breaks the chain:
function startPolling(load) {
let timer;
let stopped = false;
const tick = async () => {
await load();
if (!stopped) timer = setTimeout(tick, 5000);
};
tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}The stopped flag matters: the stop function may run while load() is in flight, and without the flag the next timer would be scheduled anyway.
Accidental globals
In sloppy-mode scripts, assigning to an undeclared name creates a property on the global object — a root:
function cacheResponse(data) {
lastResponse = data;
}lastResponse now lives as long as the page. ES modules and strict-mode code throw a ReferenceError instead, one more reason to write modules. Deliberate globals and module-level variables are roots too: whatever they hold lives for the whole session.
Logged objects
While DevTools is open, objects passed to console.log can be kept so that you can expand them later; heap snapshots even have a filter for objects retained by the console. Don't mistake that for a leak in your code, and don't ship code that logs large objects in a loop.
Mark-and-sweep and V8's generations
Bütün müasir mühərriklər mark-and-sweep ailəsindən olan izləyici (tracing) collector işlədir:
- Mark. Köklərdən başla, hər istinadı izlə və çatdığın hər obyekti işarələ.
- Sweep. İşarəsiz qalan hər şey zibildir; onun yaddaşı yeni ayrılmalar üçün boş yer siyahılarına (free list) qaytarılır.
- Compact (məcburi deyil). Sağ qalan obyektləri bir yerə yığ ki, boş yaddaş xırda "deşiklərə" bölünməsin.
Alqoritm sadədir, əsas mühəndislik isə onu səhifəni dondurmadan icra etməkdədir. V8 (Chrome, Edge, Node.js, Deno) öz collector-unu — Orinoco-nu — V8 blogunda təsvir edir. Aşağıda həmin təsvir verilib; detallar versiyadan versiyaya dəyişir.
Nəsil ideyası
Nəsil hipotezinə görə obyektlərin çoxu gənc ölür: müvəqqəti massivlər, dövrdə qurulan sətirlər, event obyektləri, aralıq nəticələr. Ona görə V8 heap-i hissələrə bölür:
- Gənc nəsil (young generation). Yeni obyektlər burada yaradılır. O, kiçikdir və Scavenger (minor GC) tərəfindən tez-tez təmizlənir. Gənc nəsil iki semi-space-ə bölünüb: canlı obyektlər dolu yarıdan boş yarıya köçürülür, geridə qalan hər şey isə tərifə görə zibildir. Xərc nə qədər yaddaş ayrıldığından yox, sağ qalanların sayından asılıdır — qısaömürlü obyektlərin ucuz olmasının səbəbi budur. Bir scavenge-dən sağ çıxan obyekt gənc nəslin aralıq hissəsinə keçir, ikincisindən də sağ çıxan isə köhnə nəslə köçürülür (promotion).
- Köhnə nəsil (old generation). Uzunömürlü obyektlər. Onu major GC (mark-compact) təmizləyir: bütün heap-i işarələyir, sweep edir və ən çox parçalanmış səhifələri sıxlaşdırır.
Yalnız gənc nəsli təmizləyə bilmək üçün V8 hansı köhnə obyektlərin gənc obyektlərə istinad etdiyini bilməlidir. Bu istinadları write barrier-lər qeydə alır, scavenger isə onları əlavə kök kimi götürür.
Pauzaları qısa saxlamaq
Böyük heap-in stop-the-world təmizlənməsi uzun müddət bloklayardı. Orinoco üç üsulu birləşdirir: paralel (pauza zamanı köməkçi thread-lər işi bölüşür), inkremental (iş JavaScript tapşırıqlarının arasında kiçik hissələrlə görülür) və konkurent (işarələmə və sweep JavaScript işləyərkən fon thread-lərində gedir). Chrome həmçinin collector-a kadrlar arasındakı boş vaxtı verə bilir.
Bu sənə niyə lazımdır
- Sızan obyektlər hər scavenge-dən sağ çıxıb köhnə nəslə düşür, orada isə hər major GC onları yenidən işarələməlidir. Yaddaş böyüyür, onunla birlikdə GC işi də.
- Durmadan böyüyən heap daha tez-tez major GC deməkdir. Bu işin çoxu main thread-dən kənarda gedir, amma hamısı yox, ona görə də zəif cihazlarda sızma çox vaxt ilk növbədə kadr itkisi (jank) kimi görünür.
Səhifənin kodu GC-ni məcburi işə sala bilməz. Node.js --expose-gc ilə gc() funksiyasını açır, DevTools-da isə "Collect garbage" düyməsi var: bunlar ölçmə alətləridir, production üçün deyil.
Every modern engine uses a tracing collector of the mark-and-sweep family:
- Mark. Start from the roots, follow every reference and mark each object reached.
- Sweep. Everything left unmarked is garbage; its memory goes back to free lists for new allocations.
- Compact (optional). Move surviving objects together so free memory is not split into small holes.
The algorithm is simple; the engineering is in running it without freezing the page. V8 (Chrome, Edge, Node.js, Deno) describes its collector, Orinoco, on the V8 blog. What follows is that description; the details change between versions.
The generational idea
The generational hypothesis says that most objects die young: temporary arrays, strings built in a loop, event objects, intermediate results. V8 therefore splits the heap:
- Young generation. New objects are allocated here. It is small and collected often by the Scavenger (the minor GC). It is split into two semi-spaces: live objects are copied out of the full half into the empty one, and whatever is left behind is garbage by definition. The cost depends on the number of survivors, not on how much was allocated — which is why short-lived allocations are cheap. An object that survives one scavenge moves to the intermediate part of the young generation; one that survives a second scavenge is promoted to the old generation.
- Old generation. Long-lived objects. It is collected by the major GC (mark-compact): marking the whole heap, sweeping, and compacting the most fragmented pages.
To collect only the young generation, V8 must know which old objects point to young ones. Write barriers record those pointers, and the scavenger treats them as extra roots.
Keeping pauses short
A stop-the-world collection of a large heap would block the for a long time. Orinoco combines three techniques: parallel (helper threads share the work during a pause), incremental (the work is split into small slices between JavaScript tasks) and concurrent (marking and sweeping run on background threads while JavaScript keeps running). Chrome can also give the collector idle time between frames.
Why this matters to you
- Leaked objects survive every scavenge and end up in the old generation, where every major GC has to mark them again. Memory grows, and GC work grows with it.
- An ever-growing heap means more frequent major collections. Most of that work is off the main thread, but not all of it, so on slow devices leaks often show up first as jank.
Page code cannot force a collection. Node.js exposes a gc() function with --expose-gc, and DevTools has a "Collect garbage" button: tools for measuring, not for production.
Detached DOM nodes, unbounded caches and captured data
DOM-dan ayrılmış node-lar
Sənəddən silinmiş node detached (ayrılmış) olur. JavaScript ona hələ də istinad edirsə, o təmizlənə bilməz. Hər node öz valideyninə və uşaqlarına istinad etdiyi üçün (parentNode, childNodes) bircə istinad bütün ayrılmış ağacı əlçatan saxlayır.
const rowsById = new Map();
function renderTable(items) {
const table = document.createElement("table");
for (const item of items) {
const row = table.insertRow();
row.insertCell().textContent = item.name;
rowsById.set(item.id, row);
}
return table;
}
function showItems(container, items) {
container.replaceChildren(renderTable(items));
}showItems səhifədəki köhnə cədvəli yenisi ilə əvəz edir, təkrarlanan id-lər üçün isə map-ə yeni sətirlər yazılır. Amma artıq göstərilməyən item-lərin yazıları heç vaxt silinmir və həmin köhnə sətirlərin hər biri bütöv köhnə cədvəli yaşadır. Render-dən əvvəl rowsById.clear() çağır və ya axtarışın istiqamətini dəyiş: sətirdən item-ə aparan WeakMap sətirlərin öz cədvəli ilə birlikdə getməsinə imkan verir.
Limitsiz keşlər
Keş kimi işlədilən Map xoş niyyətli sızmadır: yazılar daxil olur, heç nə çıxmır.
const productCache = new Map();
function getProduct(id) {
if (!productCache.has(id)) {
productCache.set(id, fetch(`/api/products/${id}`).then((r) => r.json()));
}
return productCache.get(id);
}Uzun sessiyada bu map istifadəçinin indiyədək gördüyü bütün məhsulları saxlayır. Hər keşin siyasəti olmalıdır:
- ölçü limiti — ən çoxdan istifadə olunmayan yazını çıxar.
Mapyazıları əlavə olunma sırası ilə gəzir, ona görə hər oxunuşda açarı silib yenidən əlavə etməklə kiçik LRU alınır; - yaşama müddəti (TTL) — vaxt damğası saxla və köhnəlmiş yazıları at;
- əhatə dairəsi — logout zamanı və ya funksionallıq unmount olanda keşi təmizlə.
Açar ömrünü sənin idarə etmədiyin obyektdirsə, WeakMap yazını açarla birlikdə buraxır. Limit də real olmalıdır: 10 000 böyük yazı məhduddur, amma yenə də çoxdur — retained size-ı heap snapshot-da yoxla.
Böyük datanı tutan closure-lar
öz mühitini əlçatan saxlayır. Mühərriklər yalnız closure-ların həqiqətən istifadə etdiyi dəyişənləri saxlayır, ona görə də uzunömürlü callback götürüldüyü böyük obyektə yox, ehtiyac duyduğu kiçik dəyərə istinad etməlidir:
function attachDownload(button, report) {
const { id } = report;
button.addEventListener("click", () => downloadReport(id));
}Click handler yalnız id-dən istifadə edir, ona görə də report onun üçün saxlanmır. Amma V8-də eyni scope-da yaranan closure-lar bir ortaq kontekst bölüşür: attachDownload-ın içindəki başqa bir funksiya report-dan istifadə etsəydi, handler da onu yaşadardı (closure-lar mövzusuna bax). Ağır datanı uzunömürlü callback-lər yaradan scope-lardan kənarda saxla.
Detached DOM nodes
A node removed from the document is detached. If JavaScript still references it, it cannot be collected — and because every node references its parent and its children (parentNode, childNodes), one reference keeps the whole detached tree reachable.
const rowsById = new Map();
function renderTable(items) {
const table = document.createElement("table");
for (const item of items) {
const row = table.insertRow();
row.insertCell().textContent = item.name;
rowsById.set(item.id, row);
}
return table;
}
function showItems(container, items) {
container.replaceChildren(renderTable(items));
}showItems replaces the old table on the page, and ids that repeat get new rows in the map. But entries for items that are no longer shown are never deleted, and each of those old rows keeps its entire old table alive. Call rowsById.clear() before rendering, or reverse the lookup: a WeakMap from row to item lets rows go together with their table.
Unbounded caches
A Map used as a cache is a leak with good intentions: entries go in, nothing comes out.
const productCache = new Map();
function getProduct(id) {
if (!productCache.has(id)) {
productCache.set(id, fetch(`/api/products/${id}`).then((r) => r.json()));
}
return productCache.get(id);
}Over a long session this map holds every product the user has ever seen. Every cache needs a policy:
- a size limit — evict the least recently used entry. A
Mapiterates in insertion order, so deleting and re-inserting a key on each read gives you a small LRU; - a time to live — store a timestamp and drop stale entries;
- a scope — clear it on logout or when the feature unmounts.
When the key is an object whose lifetime you don't control, a WeakMap drops the entry together with the key. And keep limits realistic: 10,000 large entries are bounded and still too much — check the retained size in a heap snapshot.
Closures holding large data
A keeps its environment reachable. Engines keep only the variables that closures actually use, so a long-lived callback should reference the small value it needs, not the large object it came from:
function attachDownload(button, report) {
const { id } = report;
button.addEventListener("click", () => downloadReport(id));
}The click handler uses only id, so report is not kept for it. In V8, though, closures created in the same scope share one context: if another function in attachDownload used report, the handler would keep it alive too (see the closures topic). Keep heavy data out of scopes that create long-lived callbacks.
WeakMap, WeakSet, WeakRef and FinalizationRegistry
Adi istinad öz hədəfini yaşadır. Zəif (weak) istinad isə yox: o, obyektə data bağlamağa imkan verir, amma obyektin yaddaşda qalması üçün səbəbə çevrilmir.
WeakMap və WeakSet
const metadata = new WeakMap();
function track(node) {
metadata.set(node, { clicks: 0, firstSeen: performance.now() });
}Map öz açarlarını zəif saxlayır: node-a başqa heç nə istinad etmədikdə yazı dəyəri ilə birlikdə təmizlənə bilər. Buna görə o, "mənə məxsus olmayan obyektlər haqqında əlavə data" üçün düzgün alətdir: DOM node-ları, kitabxanadan gələn obyektlər, sorğu obyektləri. WeakSet eyni işi üzvlük üçün görür ("bu obyekti artıq emal etmişəmmi?").
Qaydalar bu kolleksiyaların nəyi üzə çıxarmamalı olduğundan irəli gəlir:
- Açar obyekt və ya qeydiyyatsız symbol olmalıdır.
"user-1"kimi sətir açarını istənilən an yenidən yaratmaq olar, deməli o, heç vaxt "yox ola" bilməz.Symbol.for()ilə qeydə alınmış symbol-lar da eyni səbəbdən qəbul edilmir. sizeyoxdur, iterasiya yoxdur,clear()yoxdur. Yazıların siyahısını görmək collector-un nə vaxt işlədiyini müşahidə etməyə imkan verərdi, mühərriklər isə bunu açmamalıdır.
WeakMap dəyərlər üçün keş deyil. O, açarları zəif, dəyərləri isə — açar yaşadıqca — güclü saxlayır. Sətir id-lərindən böyük obyektlərə aparan map-ə WeakMap yox, ölçü limiti lazımdır. Öz açarına istinad edən dəyər isə açarı yaşatmır: WeakMap yazıları adi güclü istinad deyil, ephemeron-dur.
WeakRef və FinalizationRegistry
const registry = new FinalizationRegistry((key) => {
console.log("collected " + key);
});
function remember(report) {
registry.register(report, report.id);
return new WeakRef(report);
}
const ref = remember(loadReport());
const report = ref.deref();deref() hədəfi qaytarır, hədəf təmizləndikdən sonra isə undefined. Təzəcə WeakRef yaratdığın və ya deref() ilə aldığın hədəf cari job bitənə qədər yaşayır, yəni sinxron kodun ortasında yoxa çıxmır. FinalizationRegistry qeydə alınmış obyekt təmizləndikdən bir müddət sonra callback çağırır və ona obyektin özünü yox, held value-nu (burada report.id) ötürür.
Hər ikisi 2021-ci ilin aprelindən Baseline-dır (geniş əlçatandır), MDN isə imkan daxilində onlardan qaçmağı məsləhət görür. Spesifikasiya demək olar ki, heç bir zəmanət vermir: hədəf heç vaxt təmizlənməyə bilər, cleanup callback-i gec çağırıla və ya ümumiyyətlə çağırılmaya bilər — məsələn, tab bağlananda. Ona görə də mütləq baş verməli olan iş üçün heç vaxt finalizer-ə güvənmə: listener-ləri silmək, taymerləri təmizləmək, socket-ləri bağlamaq, datanı saxlamaq. Bunlar açıq cleanup tələb edir. Finalizer ən yaxşı halda optimallaşdırmadır, məsələn, boşalmış WeakRef-i keş map-indən silmək üçün — hətta onda da callback yazının bu arada əvəz olunmadığını yoxlamalıdır.
A normal reference keeps its target alive. A weak reference does not: it lets you attach data to an object without becoming a reason for that object to stay.
WeakMap and WeakSet
const metadata = new WeakMap();
function track(node) {
metadata.set(node, { clicks: 0, firstSeen: performance.now() });
}The map holds its keys weakly: once nothing else references node, the entry can be collected, value included. That makes it the right tool for "extra data about objects I don't own" — DOM nodes, objects from a library, request objects. A WeakSet does the same for membership ("have I already processed this object?").
The rules follow from what these collections must not reveal:
- Keys must be objects or non-registered symbols. A string key like
"user-1"can be created again at any time, so it can never be "gone". Registered symbols fromSymbol.for()are rejected for the same reason. - No
size, no iteration, noclear(). Listing the entries would let you observe when the collector ran, and engines must not expose that.
A WeakMap is not a cache for values. It holds keys weakly and values strongly, for as long as the key lives. A map from string ids to large objects needs a size limit, not a WeakMap. And a value that references its own key does not keep the key alive — WeakMap entries are ephemerons, not ordinary strong references.
WeakRef and FinalizationRegistry
const registry = new FinalizationRegistry((key) => {
console.log("collected " + key);
});
function remember(report) {
registry.register(report, report.id);
return new WeakRef(report);
}
const ref = remember(loadReport());
const report = ref.deref();deref() returns the target, or undefined once it has been collected. A target you have just created a WeakRef for, or just dereferenced, stays alive until the end of the current job, so it never disappears in the middle of synchronous code. FinalizationRegistry runs a callback some time after a registered object is collected, with the held value (report.id here), never the object itself.
Both have been Baseline (widely available) since April 2021, and MDN's advice is to avoid them where possible. The spec gives almost no guarantees: a target may never be collected, and a cleanup callback may run late or not at all — when the tab closes, for example. So never use a finalizer for something that must happen: removing listeners, clearing timers, closing sockets, saving data. Those need explicit cleanup. A finalizer is at most an optimisation, such as removing an emptied WeakRef from a cache map — and even then the callback must check that the entry was not replaced in the meantime.
Cleanup in components
Single-page tətbiqdə komponent dəfələrlə mount və unmount olur, ona görə də onun mount zamanı başlatdığı və unmount zamanı unutduğu hər şey yığılıb qalır:
function PricePanel({ symbol }) {
const [quotes, setQuotes] = useState([]);
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
setInterval(async () => {
setQuotes(await fetchQuotes(symbol));
}, 5000);
window.addEventListener("resize", () => setWidth(window.innerWidth));
}, [symbol]);
return <QuoteTable quotes={quotes} compact={width < 600} />;
}Hər mount-da və symbol-un hər dəyişməsində daha bir interval başlayır və daha bir resize listener-i əlavə olunur, onları isə heç nə dayandırmır. N ziyarətdən sonra səhifə hər beş saniyədə N dəfə sorğu göndərir, sızan hər interval isə öz closure-unu, onunla birlikdə də çoxdan unmount olmuş komponentlərin state setter-lərini yaşadır. Development rejimində Strict Mode-un əlavə setup + cleanup dövrü elə ilk mount-dan iki poller yaradır — bu, cleanup-ın çatışmadığına qəsdən verilən işarədir.
Həll setup-ın başlatdığı hər şeyi geri qaytaran cleanup-dır:
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
const id = setInterval(async () => {
try {
const response = await fetch(`/api/quotes/${symbol}`, { signal });
setQuotes(await response.json());
} catch (error) {
if (error.name !== "AbortError") console.error(error);
}
}, 5000);
window.addEventListener("resize", () => setWidth(window.innerWidth), { signal });
return () => {
clearInterval(id);
controller.abort();
};
}, [symbol]);Bir AbortController ömürləri bir-birinə bağlayır. abort() çağırışı onun signal-ı ilə qeydə alınmış bütün listener-ləri silir — ona görə də anonim resize handler-inin referansını ayrıca saxlamaq lazım deyil — və icrada olan fetch-i ləğv edir, o da AbortError ilə reject olur. Hələ gəlməkdə olan cavab gövdəsinin oxunması da ləğv olunur, beləliklə gecikən cavab heç vaxt setQuotes-a çatmır.
Hər abunəliyin sahibi olmalıdır
Eyni qayda komponentin abunə olduğu hər şeyə aiddir: store listener-ləri, WebSocket-lər, ResizeObserver və IntersectionObserver (disconnect()), media query listener-ləri, üçüncü tərəf vidjetləri (destroy()). Abunəlik API-lərinin çoxu unsubscribe funksiyası qaytarır; onu effektdən qaytarmaq elə cleanup-ın özüdür. Xarici store-dan dəyər oxumaq üçün isə useSyncExternalStore abunə olmağı da, abunəlikdən çıxmağı da sənin yerinə edir.
İncident-in yoxlamaları da məhz bunu ölçür: səhifədən çıxdıqdan sonra intervalların və qlobal listener-lərin sayı ilkin səviyyəyə qayıtmalı, sorğu tezliyi isə bir poller səviyyəsində qalmalıdır.
In a single-page app a component mounts and unmounts many times, so whatever it starts on mount and forgets on unmount piles up:
function PricePanel({ symbol }) {
const [quotes, setQuotes] = useState([]);
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
setInterval(async () => {
setQuotes(await fetchQuotes(symbol));
}, 5000);
window.addEventListener("resize", () => setWidth(window.innerWidth));
}, [symbol]);
return <QuoteTable quotes={quotes} compact={width < 600} />;
}Every mount, and every change of symbol, starts one more interval and adds one more resize listener, and nothing ever stops them. After N visits the page polls N times every five seconds, and each leaked interval keeps its closure — and with it the state setters of components that are long unmounted. In development, Strict Mode's extra setup + cleanup cycle makes it two pollers from the very first mount: a deliberate hint that the cleanup is missing.
The fix is a cleanup that undoes everything the setup started:
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
const id = setInterval(async () => {
try {
const response = await fetch(`/api/quotes/${symbol}`, { signal });
setQuotes(await response.json());
} catch (error) {
if (error.name !== "AbortError") console.error(error);
}
}, 5000);
window.addEventListener("resize", () => setWidth(window.innerWidth), { signal });
return () => {
clearInterval(id);
controller.abort();
};
}, [symbol]);One AbortController ties the lifetimes together. Calling abort() removes every listener registered with its signal — so the anonymous resize handler needs no saved reference — and cancels an in-flight fetch, which then rejects with an AbortError. Reading a response body that is still arriving is cancelled too, so a late response never reaches setQuotes.
Every subscription needs an owner
The same rule applies to everything a component subscribes to: store listeners, WebSockets, ResizeObserver and IntersectionObserver (disconnect()), media-query listeners, third-party widgets (destroy()). Most subscribe APIs return an unsubscribe function; returning it from the effect is the cleanup. For reading a value from an external store, useSyncExternalStore subscribes and unsubscribes for you.
To verify a fix like this, leave the screen and check that the number of intervals and global listeners is back to its baseline.
Finding leaks with Chrome DevTools
Təxmin etmə, ölç. Etibarlı iş axını belədir:
- Trendi təsdiqlə. Performance panelində Memory checkbox-unu aç və şübhəli əməliyyatı təkrarlayarkən (dialoqu on dəfə aç-bağla) yazını başlat. Əvvəldə və sonda Collect garbage düyməsini bas. JS heap, DOM node və listener sayğacları ilkin səviyyəyə qayıtmalıdır; heç vaxt enməyən pilləkən sızmadır. Chrome-un Task Manager-i (More tools > Task manager, JavaScript memory sütunu aktiv olmaqla) tez baxmaq üçün canlı rəqəm verir.
- Heap snapshot götür. Memory panelində Heap snapshot seç. Snapshot götürmək həmişə garbage collection ilə başlayır, ona görə gördüyün hər şey həqiqətən əlçatandır. Üç snapshot götür: ilkin vəziyyət, əməliyyatı bir neçə dəfə təkrarladıqdan sonra və onu geri qaytardıqdan (görünüşü bağladıqdan) sonra.
- Müqayisə et. Comparison görünüşü hər konstruktor üzrə iki snapshot arasında neçə obyektin əlavə olunduğunu və silindiyini, həmçinin fərqi (# Delta sütunu) göstərir. Əməliyyatı on dəfə təkrarla və on vahid artan sayları axtar. Summary görünüşündə Objects allocated between Snapshot 1 and Snapshot 2 filtri oxşar suala cavab verir.
- Retainers zəncirini izlə. Şübhəli obyekti seç: Retainers paneli onu yaşadan istinad zəncirini kökə doğru göstərir. Sızma adətən gözləmədiyin ilk halqadır —
Windowlistener-i, taymer, modul səviyyəsindəkiMap. Shallow size-a (obyektin öz ölçüsü) yox, Retained size-a (obyektlə birlikdə azad olunacaq yaddaş) görə sırala. - Ayrılmış node-ları axtar. Class filter-ə
Detachedyaz və ya Objects retained by detached nodes filtrini seç; Chrome-un yeni versiyalarında Memory panelində ayrıca Detached elements profili də var.
Allocations on timeline yaddaş ayrılmalarını zaman üzrə yazır: mavi zolaqlar yazının sonunda hələ canlı olan obyektlərdir, boz zolaqlar isə artıq təmizlənib. Hər təkrarda yaranan mavi zolaqlar sızan obyektləri yaradan koda işarə edir. Allocation sampling ayrılmaları az əlavə yüklə funksiyalar üzrə bölüşdürür, bu da uzun yazılar üçün əlverişlidir.
performance.memory sızma detektoru deyil
performance.memory (usedJSHeapSize, totalJSHeapSize, jsHeapSizeLimit) qeyri-standartdır, deprecated-dir və yalnız Chromium əsaslı brauzerlərdə var. MDN onun rəqəmlərini etibarsız sayır: səhifələr bir heap-i bölüşə bilər, worker-lər və cross-site iframe-lər isə ayrıca heap-də olur. Onu əvəz etməli olan performance.measureUserAgentSpecificMemory() eksperimentaldır, Baseline deyil və yalnız secure, cross-origin isolated səhifədə işləyir. Bunlardan real istifadəçilərdən gələn təxmini trendlər üçün istifadə et, sızmanın sübutu kimi yox.
Node.js-də də eyni alətlər var: DevTools-u --inspect ilə qoş və ya koddan v8.writeHeapSnapshot() ilə snapshot yaz və onu Memory panelində aç.
Platformadakı watchlist-leak incident-i bu iş axınını işləyən tətbiqdə məşq etməyə imkan verir.
Don't guess — measure. A reliable workflow:
- Confirm the trend. In the Performance panel, turn on the Memory checkbox and record while you repeat the suspect action (open and close the dialog ten times). Click Collect garbage at the start and at the end. The JS heap, DOM node and listener counters should come back to a baseline; a staircase that never comes down is a leak. Chrome's Task Manager (More tools > Task manager, with the JavaScript memory column turned on) gives a quick live number.
- Take heap snapshots. In the Memory panel choose Heap snapshot. Taking a snapshot always starts with a garbage collection, so what you see is really reachable. Take three: a baseline, one after repeating the action several times, and one after undoing it (closing the view).
- Compare. The Comparison view shows, per constructor, how many objects were added and deleted between two snapshots and the change (the # Delta column). Repeat the action ten times and look for counts that grew by ten. In the Summary view, the filter Objects allocated between Snapshot 1 and Snapshot 2 answers a similar question.
- Follow the Retainers. Select a suspicious object: the Retainers pane shows the chain of references that keeps it alive, back towards a root. The leak is usually the first link you didn't expect — a
Windowlistener, a timer, a module-levelMap. Sort by Retained size (what would be freed together with the object), not Shallow size (the object's own size). - Look for detached nodes. Type
Detachedin the class filter or pick Objects retained by detached nodes; recent Chrome versions also offer a Detached elements profile in the Memory panel.
Allocations on timeline records allocations over time: blue bars are objects still alive at the end of the recording, gray bars were collected. Blue bars that appear on every repetition point to the code that allocates the leaked objects. Allocation sampling attributes allocations to functions with little overhead, which suits long recordings.
performance.memory is not a leak detector
performance.memory (usedJSHeapSize, totalJSHeapSize, jsHeapSizeLimit) is non-standard, deprecated and available only in Chromium-based browsers, and MDN calls its numbers unreliable: pages can share a heap, while workers and cross-site iframes have their own. Its proposed replacement, performance.measureUserAgentSpecificMemory(), is experimental, not Baseline, and works only in a secure, cross-origin-isolated page. Use these for rough trends from the field, never as proof of a leak.
In Node.js the same tools are available: attach DevTools with --inspect, or write a snapshot from code with v8.writeHeapSnapshot() and open it in the Memory panel.
The platform's watchlist-leak incident lets you practise this workflow on a running app.
Interview tips
30 saniyəlik cavab. "JavaScript köklərdən əlçatmaz olan obyektləri təmizləyir; köklər qlobal obyekt, call stack və host-un saxladığı şeylərdir, məsələn, listener-lər və taymerlər. Sızma hələ əlçatan, amma artıq lazım olmayan yaddaşdır: window üzərindəki listener-lər, heç kimin təmizləmədiyi intervallar, DOM-dan ayrılmış node-lar, yalnız böyüyən keşlər. Sızmanı heap snapshot-larla təsdiqləyirəm və hər abunəliyə cleanup verməklə düzəldirəm."
Gözlənilən suallar
- JavaScript-də garbage collection necə işləyir? Köklərdən əlçatanlıq, mark-and-sweep və dövri istinadların niyə problem olmadığı. Senior vəzifə üçün nəsilləri də əlavə et: gənc obyektlər üçün Scavenger, köhnələr üçün mark-compact, pauzaları qısaltmaq üçün inkremental və konkurent işarələmə.
- Garbage collection olan dildə sızma ola bilərmi? Bəli. İki konkret mənbə və onların həllini de.
Map, yoxsaWeakMap? Zəif açarlar, yalnız obyekt (və ya qeydiyyatsız symbol) açarlar, iterasiya vəsizeyoxdur — çünki təmizlənmə müşahidə oluna bilməməlidir. Ondan nə vaxt istifadə etməyəcəyini də de: sətir açarları, dəyərlər üçün keş.- Tətbiq bir saatdan sonra yavaşlayır. Necə araşdırarsan? Performance panelində trend → üç snapshot → Comparison → Retainers. Development-də Strict Mode-un əlavə effekt dövrünün çatışmayan cleanup-ları erkən üzə çıxardığını da qeyd et.
- Bağlantıları
FinalizationRegistrycallback-ində bağlayardınmı? Xeyr: callback-in çağırılacağına zəmanət yoxdur.
Bal itirdən səhvlər
- "Dəyişənə
nullmənimsətmək yaddaşı azad edir." Bu, yalnız bir istinadı silir; obyekti collector sonra təmizləyir, həm də yalnız ona başqa heç nə çatmırsa. - "Dövri istinadlar sızma yaradır." İzləyici (tracing) collector-larda yox.
- "Silinmiş elementlər listener-lərini həmişə sızdırır." Yalnız elementə hələ də nəsə istinad edirsə və ya listener elementdən uzun yaşayan hədəfə bağlıdırsa.
performance.memory-ni və ya Task Manager-dəki rəqəmi sübut saymaq. Sübut snapshot müqayisəsi və retainer zənciridir.
Senior səviyyəni göstərən məqamlar
Yalnız API-lərdən yox, ömürlərdən danış: hər abunəliyin sahibi kimdir, hər keşi nə məhdudlaşdırır və komanda reqressiyaları necə tutur. Məsələn, bir axını təkrarlayıb intervalların, listener-lərin və DOM node-larının sayının ilkin səviyyəyə qayıtdığını yoxlayan end-to-end test.
A 30-second answer. "JavaScript frees objects that are unreachable from the roots — globals, the call stack and what the host holds, like listeners and timers. A leak is memory that is still reachable but no longer needed: listeners on window, intervals nobody clears, detached DOM nodes, caches that only grow. I confirm a leak with heap snapshots and fix it by giving every subscription a cleanup."
Questions you are likely to get
- How does garbage collection work in JavaScript? Reachability from roots, mark-and-sweep, and why cycles are not a problem. For senior roles add generations: the Scavenger for young objects, mark-compact for old ones, incremental and concurrent marking to keep pauses short.
- Can a garbage-collected language leak? Yes. Give two concrete sources and their fixes.
MaporWeakMap? Weak keys, object (or non-registered symbol) keys only, no iteration orsize— because collection must not be observable. Say when you would not use it: string keys, caches of values.- The app slows down after an hour. How do you investigate? Performance panel trend → three snapshots → Comparison → Retainers. Mention that Strict Mode's extra effect cycle in development exposes missing cleanups early.
- Would you close connections in a
FinalizationRegistrycallback? No: the callback is not guaranteed to run.
Mistakes that cost points
- "Setting a variable to
nullfrees the memory." It removes one reference; the collector frees the object later, and only if nothing else reaches it. - "Circular references leak." Not with tracing collectors.
- "Removed elements always leak their listeners." Only if something still references the element, or the listener sits on a target that outlives it.
- Treating
performance.memoryor the Task Manager number as proof. Snapshot comparisons and retainer chains are the proof.
Senior signal
Talk about lifetimes, not only APIs: who owns each subscription, what bounds each cache, and how the team catches regressions — for example an end-to-end check that repeats a flow and asserts that intervals, listeners and DOM node counts return to their baseline.
What to check when reviewing code for memory leaks
Bu siyahını yazmadığın kodu review edəndə işlət: komanda yoldaşının pull request-i, kitabxananın issue tracker-indəki snippet və ya AI assistentin təklifi. Hər uzunömürlü istinad üçün soruş: onu kim silir və nə vaxt? Cavab "heç kim"dirsə, yaddaş hər təkrarla artacaq, köhnə handler-lər isə işləməyə davam edəcək.
- Setup-ın başlatdığı hər şeyin uyğun dayandırılması varmı?
windowvə yadocumentüzərindəki həraddEventListener,setInterval, özünü yenidən planlaşdıransetTimeout, abunəlik və ya observer üçün uyğunremoveEventListener,clearInterval,clearTimeout, unsubscribe və yadisconnect()olmalıdır. React-də bunun yeri effektin cleanup-ıdır; development-də Strict Mode-un əlavə setup + cleanup dövrü çatışmayan cleanup-ı üzə çıxarır. - Listener eyni funksiya referansı ilə silinirmi?
removeEventListener-ə təzə yazılmış arrow funksiya ötürsən, heç nə silinmir. Saxlanmış funksiya və ya{ signal }iləcontroller.abort()gözlə. - Modul səviyyəsindəki massiv,
Mapvə ya keş yalnız böyüyürmü? Siyasət tələb et: ölçü limiti, yaşama müddəti (TTL) və ya logout zamanı təmizləmə.WeakMapyalnız obyekt açarlarına uyğundur. - Kod DOM-dan silinmiş node-lara istinad saxlayırmı? Dəyişəndə və ya
Map-də qalan bircə istinad bütün ayrılmış ağacı yaşadır. - Uzunömürlü callback bir sahə üçün böyük obyekti tuturmu? istinad etdiyi şeyləri əlçatan saxlayır; kiçik dəyəri əvvəlcədən ayrıca götür, məsələn,
const { id } = report. - Mütləq baş verməli olan cleanup
FinalizationRegistry-yə həvalə olunubmu? Onun callback-i gec çağırıla və ya heç çağırılmaya bilər, ona görə də listener-lər, taymerlər və socket-lər açıq cleanup tələb edir. - Sızma təxminlə yox, ölçü ilə təsdiqlənirmi? Əməliyyatı on dəfə təkrarla və DevTools-un Memory panelində heap snapshot-ları müqayisə et: sayı on vahid artan konstruktor ipucudur, onun Retainers siyahısı isə onu nəyin yaşatdığını göstərir.
Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. For each long-lived reference, ask who removes it and when; if nobody does, memory climbs with every repetition and old handlers keep running.
- Does everything the setup starts have a matching stop? Each
addEventListeneronwindowordocument,setInterval, self-reschedulingsetTimeout, subscription or observer needs itsremoveEventListener,clearInterval,clearTimeout, unsubscribe ordisconnect(). In React it goes in the effect's cleanup; Strict Mode's extra setup and cleanup in development exposes a missing one. - Is the listener removed with the same function reference?
removeEventListenerwith a freshly written arrow function removes nothing. Expect a saved function, or{ signal }withcontroller.abort(). - Does a module-level array,
Mapor cache only grow? Ask for a policy: a size limit, a time to live or clearing on logout. AWeakMapfits only object keys. - Does the code keep references to removed DOM nodes? One reference in a variable or a
Mapkeeps the whole detached tree alive. - Does a long-lived callback capture a large object for one field? A keeps what it references reachable; copy the small value first, for example
const { id } = report. - Is required cleanup left to
FinalizationRegistry? Its callback may run late or never, so listeners, timers and sockets need explicit cleanup. - Is the leak measured, not guessed? Repeat the action ten times and compare heap snapshots in the DevTools Memory panel: a constructor whose count grew by ten is a lead, and its Retainers show what keeps it alive.
Check your understanding
Practise this
Hands-on work that uses this topic.