Event loop
Tək thread-də işləyən JavaScript taymerləri, şəbəkə cavablarını və istifadəçi hərəkətlərini səhifəni dondurmadan necə emal edir: call stack, tapşırıq və mikrotapşırıq növbələri, render, eləcə də bunun React və performans üçün mənası.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
İlkin şərt yoxdur.
Bu mövzu Junior səviyyəsindən başlayır.
Event loop nədir və JavaScript-ə nə üçün lazımdır
JavaScript kodu tək bir thread-də icra olunur. Hər an kodun yalnız bir hissəsi işləyir və mühərrik bunu vasitəsilə izləyir: funksiya çağırılanda stack-ə yeni frame əlavə olunur, funksiya qayıdanda həmin frame çıxarılır. Stack-də nəsə olduqca başqa heç nə icra oluna bilməz.
Veb səhifə isə "eyni vaxtda" baş verən çoxlu işlə məşğul olmalıdır: taymerin vaxtı bitir, şəbəkədən cavab gəlir, istifadəçi düyməyə klikləyir, ekran yenidən çəkilməlidir. JavaScript bunların hər birini oturub gözləsəydi, səhifə donardı.
Ona görə də iş iki tərəf arasında bölünür:
- JavaScript mühərriki (V8, SpiderMonkey, JavaScriptCore) kodu icra edir və call stack-i idarə edir. Dilin özündə nə taymer var, nə şəbəkə, nə də klik.
- Host mühit — brauzer və ya Node.js — bu imkanları təqdim edir. Brauzerdə onlara deyilir. Gözləmə işini host sənin kodundan kənarda görür, nəticə hazır olanda isə sonradan icra olunmaq üçün növbəyə qoyur.
host-un bu iki tərəfi birləşdirən mexanizmidir. Sadələşdirilmiş psevdokodla:
while (true) {
const task = queue.takeNext();
task.run();
}Hər dövrdə növbədən bir callback götürülür və call stack yenidən boşalana qədər icra olunur. Buna run-to-completion (sona qədər icra) deyilir: işləyən funksiyanı yarı yolda başqa callback kəsə bilməz. Bu, kodu proqnozlaşdırıla bilən edir — iki callback eyni dəyişəni eyni anda dəyişmir. Amma bu həm də o deməkdir ki, bir yavaş funksiya səhifədəki hər şeyi, o cümlədən klikləri və ekranın yenilənməsini bloklayır. Əsl dövrün bir neçə əlavə addımı da var (mikrotapşırıqlar və render); onlara Middle səviyyəsində baxacağıq.
"Tək thread" dedikdə səhifənin nəzərdə tutulur. Web Worker-lər JavaScript-i ayrı thread-lərdə icra edir və hər worker-in öz event loop-u olur.
JavaScript runs your code on a single thread. At any moment exactly one piece of JavaScript is executing, and the engine keeps track of it with the : calling a function pushes a frame onto the stack, returning from it pops the frame. While something is on the stack, nothing else can run.
A web page, however, has to deal with many things that happen "at the same time": a timer expires, a network response arrives, the user clicks a button, the screen needs to be redrawn. If JavaScript had to sit and wait for each of these, the page would freeze.
So the work is split between two parts:
- The JavaScript engine (V8, SpiderMonkey, JavaScriptCore) executes code and manages the call stack. The language itself has no timers, no network and no clicks.
- The host environment — the browser or Node.js — provides those capabilities. In the browser they are called . The host does the waiting outside your code and, when a result is ready, queues a to run later.
The is the host's mechanism that connects the two. In simplified pseudocode:
while (true) {
const task = queue.takeNext();
task.run();
}Each iteration takes one queued callback and runs it until the call stack is empty again. This is called run-to-completion: a running function is never interrupted halfway by another callback. It keeps code predictable — two callbacks never change the same variable at the same time — but it also means that one slow function blocks everything else on the page, including clicks and screen updates. The real loop has a few more steps (microtasks and rendering); the Middle level adds them.
"Single-threaded" refers to the page's . Web Workers run JavaScript on separate threads, and each worker has its own event loop.
Call stack, Web API-lər və tapşırıq növbəsi
Taymerlə nə baş verdiyini addım-addım izləyək:
console.log("one");
setTimeout(() => console.log("three"), 0);
console.log("two");console.log("one")əlavə olunur, icra olunur və oradan çıxarılır.setTimeoutbrauzerdən taymeri işə salmağı xahiş edir və dərhal qayıdır. Taymerin özü JavaScript deyil və stack-də yer tutmur.console.log("two")icra olunur. Skript bitir, call stack boşalır.- Bu arada taymerin vaxtı artıq bitib, ona görə brauzer callback üçün tapşırığı qoyub.
- call stack-in boş olduğunu görür, tapşırığı götürür və icra edir:
threeçap olunur.
Deməli, setTimeout(fn, 0) "fn-i indi icra et" demək deyil. Onun mənası budur: "ən azı 0 ms keçəndən sonra fn-i yeni tapşırıq kimi növbəyə qoy". Gecikmə minimumdur, zəmanət deyil: cari kod thread-i 200 ms məşğul saxlasa, callback ən azı o qədər gözləyəcək.
Hər asinxron əməliyyatda eyni hissələr iştirak edir:
| Hissə | Kimə aiddir | Vəzifəsi |
|---|---|---|
| Call stack | JS mühərriki | Kodu icra edir, hər dəfə bir frame |
| Web API-lər | Brauzer | Taymerlər, şəbəkə, DOM hadisələri — JavaScript-dən kənarda görülən iş |
| Tapşırıq növbəsi | Brauzer | Öz növbəsini gözləyən callback-lər |
| Event loop | Brauzer | Call stack boşalan kimi növbəti tapşırığı icra edir |
Klik də eyni cür işləyir: brauzer kliki qeydə alır, hadisəni göndərən tapşırığı növbəyə qoyur və sənin click listener-in yalnız stack boşalanda işə düşür. Kod uzun bir dövrün ortasındadırsa, klik itmir — sadəcə növbədə gözləyir.
Əslində brauzerdə bir neçə tapşırıq növbəsi var (məsələn, taymerlər və istifadəçi hadisələri üçün) və növbəti dəfə hansına xidmət edəcəyini brauzer özü seçir. Hələlik bunu ardıcıl emal olunan tək növbə kimi təsəvvür et.
Follow what happens with a timer:
console.log("one");
setTimeout(() => console.log("three"), 0);
console.log("two");console.log("one")is pushed onto the , runs and is popped.setTimeoutasks the browser to start a timer and returns immediately. The timer itself is not JavaScript and does not occupy the stack.console.log("two")runs. The script ends, and the call stack is empty.- Meanwhile the timer has expired, so the browser has put a task for the callback into the .
- The sees an empty call stack, takes the task and runs it:
threeis logged.
So setTimeout(fn, 0) does not mean "run fn now". It means "queue fn as a new task once at least 0 ms have passed". The delay is a minimum, not a guarantee: if the current code keeps the thread busy for 200 ms, the callback waits at least that long.
The same pieces take part in every asynchronous operation:
| Piece | Owned by | Job |
|---|---|---|
| Call stack | JS engine | Runs code, one frame at a time |
| Web APIs | Browser | Timers, network, DOM events — work done outside your JavaScript |
| Task queue | Browser | Callbacks waiting for their turn |
| Event loop | Browser | Runs the next task whenever the call stack is empty |
A click works the same way: the browser notices the click, queues a task that dispatches the event, and your click listener runs only when the stack is free. If your code is in the middle of a long loop, the click is not lost — it waits in the queue.
Strictly speaking, a browser has several task queues (for example, for timers and for user input) and decides which one to serve next. For now, picture a single queue processed in order.
Nümunə: icra ardıcıllığını izləyək
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
function heavy() {
const end = Date.now() + 100;
while (Date.now() < end) {}
console.log("C");
}
heavy();
console.log("D");Nəticə: A, C, D, B. Üstəlik, gecikməsi 0 olsa da, B təxminən 100 ms-dən sonra görünür.
Addım-addım:
Asinxron çap olunur.setTimeoutcallback-i brauzerin taymerinə ötürür və qayıdır. Hələ heç nə növbəyə düşməyib.heavy()100 ms boyunca boş dövr icra edir. Taymerin vaxtı demək olar ki, dərhal bitir və brauzer callback-i tapşırıq növbəsinə qoyur — amma call stack boş deyil, ona görə callback gözləməli olur.heavyCçap edir və qayıdır.- Skript
Dçap edir və bitir; call stack artıq boşdur. - Event loop gözləyən tapşırığı götürüb icra edir:
B.
Eyni izləmə cədvəl şəklində:
| Addım | Call stack | Tapşırıq növbəsi | Çap olunan |
|---|---|---|---|
| 1 | skript | — | A |
| 2 | skript → setTimeout | — | — |
| 3 | skript → heavy | taymer callback-i | — |
| 4 | skript → heavy | taymer callback-i | C |
| 5 | skript | taymer callback-i | D |
| 6 | taymer callback-i | — | B |
Nəyi yadda saxlamalı
- Sinxron kod həmişə birinci bitir. Taymerlərin və hadisələrin növbəyə qoyduğu callback-lər sonra, bir-bir icra olunur.
- Taymerin gecikməsi callback-in icra oluna biləcəyi ən erkən andır, mütləq icra olunacağı an deyil.
- Məşğul kod hər şeyi gecikdirir. Brauzerdə eyni 100 ms-lik dövr klik handler-lərini və ekranın yenilənməsini də ləngidərdi: dövr zamanı edilən kliklər yalnız
Dçap olunandan sonra emal olunur.
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
function heavy() {
const end = Date.now() + 100;
while (Date.now() < end) {}
console.log("C");
}
heavy();
console.log("D");The output is A, C, D, B — and B appears only after about 100 ms, even though its delay is 0.
Step by step:
Ais logged synchronously.setTimeouthands the callback to the browser's timer and returns. Nothing is queued yet.heavy()runs a busy loop for 100 ms. Almost immediately the timer expires and the browser puts the callback into the task queue — but the call stack is not empty, so the callback has to wait.heavylogsCand returns.- The script logs
Dand finishes; the call stack is now empty. - The event loop takes the waiting task and runs it:
B.
The same trace as a table:
| Step | Call stack | Task queue | Logged |
|---|---|---|---|
| 1 | script | — | A |
| 2 | script → setTimeout | — | — |
| 3 | script → heavy | timer callback | — |
| 4 | script → heavy | timer callback | C |
| 5 | script | timer callback | D |
| 6 | timer callback | — | B |
What to take away
- Synchronous code always finishes first. Callbacks queued by timers and events run later, one at a time.
- A timer's delay is the earliest moment the callback may run, not the moment it will run.
- Busy code delays everything. In a browser, the same 100 ms loop would also delay click handlers and screen updates: clicks made during the loop are handled only after
Dis logged.
Mikrotapşırıqlar və tapşırıqlar
əlavə, hər event loop-un bir dənə mikrotapşırıq növbəsi var. bu mənbələrdən yaranır:
- reaksiyaları —
then,catchvəfinally-yə ötürülən callback-lər; asyncfunksiyanınawait-dən sonrakı davamı;queueMicrotask(fn);MutationObservercallback-ləri.
Tapşırıqlar (onlara çox vaxt makrotapşırıq da deyilir) isə taymerlərdən, istifadəçi hadisələrindən, şəbəkə hadisələrindən, postMessage-dən və s. yaranır.
Qayda
Hər tapşırıqdan sonra brauzer mikrotapşırıq checkpoint-i keçirir: növbə boşalana qədər mikrotapşırıqları icra edir — növbə boşaldılarkən əlavə olunanlar da daxil olmaqla. Yalnız bundan sonra event loop render-ə və ya növbəti tapşırığa keçə bilər. Checkpoint həmçinin hər callback bitib call stack boşalanda baş verir — məsələn, real istifadəçi klikində iki hadisə listener-i arasında.
setTimeout(() => console.log("task"), 0);
Promise.resolve().then(() => console.log("microtask 1"));
queueMicrotask(() => console.log("microtask 2"));
console.log("sync");Nəticə: sync, microtask 1, microtask 2, task. Hər iki mikrotapşırıq skript bitən kimi icra olunur, taymer callback-i isə növbəti tapşırıq dövrünü gözləyir.
async/await bura necə uyğunlaşır
promise-lər üzərində qurulmuş sintaksisdir. İlk await-ə qədər olan kod sinxron icra olunur; funksiyanın qalan hissəsi isə gözlənilən dəyər yekunlaşandan sonra mikrotapşırıq kimi davam edir:
async function save() {
console.log("before");
await write();
console.log("after");
}Bu funksiya təxminən belə işləyir:
function save() {
console.log("before");
return Promise.resolve(write()).then(() => {
console.log("after");
});
}Məhz buna görə artıq hazır olan dəyəri gözləyəndə belə — hətta await null yazanda — funksiya cari sinxron kod bitənə qədər dayanır.
Nəyi kim müəyyən edir
ECMAScript spesifikasiyası promise job-larını müəyyən edir, event loop-u isə yox. Dövrü host müəyyən edir: brauzerlərdə HTML spesifikasiyası promise job-larını mikrotapşırıq kimi icra edir. Node.js-in öz dövrü var, lakin promise callback-ləri bir-birinə nisbətən eyni ardıcıllıqla işləyir.
Besides the , every event loop has a single microtask queue. come from:
- reactions — the callbacks passed to
then,catchandfinally; - the continuation of an
asyncfunction afterawait; queueMicrotask(fn);MutationObservercallbacks.
Tasks (often called macrotasks) come from timers, user input, network events and postMessage, among others.
The rule
After every task, the browser performs a microtask checkpoint: it runs microtasks until the queue is empty — including microtasks queued while it is draining. Only then can the loop move on to rendering or to the next task. A checkpoint also happens whenever the call stack becomes empty after a callback, for example between two event listeners during a real user click.
setTimeout(() => console.log("task"), 0);
Promise.resolve().then(() => console.log("microtask 1"));
queueMicrotask(() => console.log("microtask 2"));
console.log("sync");Output: sync, microtask 1, microtask 2, task. Both microtasks run as soon as the script finishes; the timer callback waits for the next task turn.
Where async/await fits
is syntax on top of promises. The code before the first await runs synchronously; the rest of the function resumes as a microtask once the awaited value settles:
async function save() {
console.log("before");
await write();
console.log("after");
}behaves roughly like:
function save() {
console.log("before");
return Promise.resolve(write()).then(() => {
console.log("after");
});
}That is why await on a value that is already available — even await null — still pauses the function until the current synchronous code has finished.
Who defines what
The ECMAScript spec defines promise jobs but no event loop. The host defines the loop: in browsers, the HTML spec runs promise jobs as microtasks. Node.js has its own loop, but promise callbacks follow the same order relative to each other.
Render harada baş verir: kadrlar və requestAnimationFrame
Brauzer hər tapşırıqdan sonra render etmir. O, render imkanı (rendering opportunity) yarananda render edir. Bu, adətən ekranın yenilənmə tezliyinə uyğun gəlir (60 Hz ekranda ən çox təxminən 16,7 ms-dən bir), səhifə ayaqlaşa bilmədikdə daha seyrək olur, gizli tabda isə xeyli seyrəkləşir və ya ümumiyyətlə baş vermir. Belə imkan yarananda event loop tapşırıqların arasında "render-i yenilə" addımını icra edir. Sadələşdirsək, bu addımda brauzer:
resizevəscrollhadisələrini göndərir;- callback-lərini icra edir;
- stilləri yenidən hesablayır və aparır;
- edir və yeni kadrı ekrana çıxarır.
Bundan üç nəticə çıxır.
Tapşırığın ortasında və ya mikrotapşırıqlar icra olunarkən heç nə çəkilmir. Bir tapşırıq ərzində edilən bütün DOM dəyişiklikləri ekranda birlikdə görünür:
box.style.display = "block";
box.style.display = "none";İstifadəçi qutunu heç vaxt görmür, çünki bu iki sətir arasında render baş verə bilməz.
Vizual yeniləmələrin yeri requestAnimationFrame-dir. setTimeout ilə qurulan dövr kadrlarla uzlaşmır: callback iki kadr arasında iki dəfə işləyə (boş yerə görülən iş) və ya bir kadrı ötürə bilər (gözə çarpan titrəmə, yəni jank). requestAnimationFrame isə hər kadrda bir dəfə, stil və layout hesablanmazdan dərhal əvvəl işləyir və callback-ə timestamp ötürür — animasiyanı ona əsaslanaraq qurmaq olar:
function step(timestamp) {
box.style.transform = `translateX(${(timestamp / 10) % 300}px)`;
requestAnimationFrame(step);
}
requestAnimationFrame(step);Uzun tapşırıqlar input-u və paint-i bloklayır. tapşırıq icra olunduqca brauzer nə klik handler-ini işə sala, nə də yeni kadr göstərə bilir. Main thread-i 50 ms və ya daha çox məşğul saxlayan tapşırıq brauzerin performans API-lərində long task (uzun tapşırıq) sayılır. Klik handler-i 300 ms çəkirsə, səhifə ən azı 300 ms ərzində heç bir vizual reaksiya göstərə bilmir — Core Web Vitals metriki olan INP (Interaction to Next Paint) məhz bu cür gecikməni ölçür.
The browser does not render after every task. It renders when it has a rendering opportunity — typically in step with the display's refresh rate (on a 60 Hz screen, at most about every 16.7 ms), less often if the page can't keep up, and much less often or not at all in a hidden tab. Then the event loop runs an "update the rendering" step between tasks. Simplified, it:
- fires
resizeandscrollevents; - runs callbacks;
- recalculates styles and runs ;
- and presents the new frame.
Three consequences follow.
Nothing is drawn in the middle of a task or while microtasks drain. All DOM changes made in one task appear together:
box.style.display = "block";
box.style.display = "none";The user never sees the box, because no rendering can happen between these two lines.
Visual updates belong in requestAnimationFrame. A setTimeout loop is not aligned with frames: a callback may run twice between two frames (wasted work) or miss a frame (visible jank). requestAnimationFrame runs once per frame, right before style and layout, and passes a timestamp the animation can be based on:
function step(timestamp) {
box.style.transform = `translateX(${(timestamp / 10) % 300}px)`;
requestAnimationFrame(step);
}
requestAnimationFrame(step);Long tasks block input and paint. While a task runs on the , the browser can neither run a click handler nor show a new frame. A task that keeps the main thread busy for 50 ms or more counts as a long task in the browser's performance APIs. If a click handler takes 300 ms, the page can't show any visual response for at least 300 ms — the kind of delay the Core Web Vitals metric INP (Interaction to Next Paint) measures.
Tez-tez rast gəlinən səhvlər
Mikrotapşırıq aclığı (starvation)
Checkpoint növbəni tam boşalana qədər icra edir. Ona görə də daim yeni mikrotapşırıq əlavə edən mikrotapşırıq event loop-un irəliləməsinə heç vaxt imkan vermir:
function loop() {
queueMicrotask(loop);
}
loop();Səhifə donur: nə taymerlər işləyir, nə input emal olunur, nə də render baş verir. Rekursiv promise zənciri də eyni nəticəyə gətirir. setTimeout ilə yazılmış variant isə səhifəni dondurmur, çünki hər callback ayrıca tapşırıqdır və brauzer onların arasında render edə, input-u emal edə bilir.
Promise ağır işi fona keçirmir
Ağır işi promise-ə bükmək onu main thread-dən çıxarmır. new Promise(...)-in executor funksiyası sinxron icra olunur, then callback-i isə mikrotapşırıq kimi işləyir — yenə də növbəti render-dən əvvəl. Səhifənin cavab verməyə davam etməsi üçün işi bir neçə tapşırığa böl və ya Web Worker-ə köçür (Senior səviyyəsinə bax).
Taymerlər dəqiq deyil
- Gecikmə minimumdur; məşğul main thread bütün taymerləri təxirə salır.
- HTML spesifikasiyası iç-içə taymerləri məhdudlaşdırır:
setTimeoutçağırışları beş səviyyədən dərin iç-içə olanda 4 ms-dən kiçik gecikmələr 4 ms-ə qaldırılır. - Brauzerlər fon tablarında taymerləri yavaşladır (throttling), dəqiq qaydalar isə brauzerdən brauzerə fərqlənir.
Animasiyalar üçün requestAnimationFrame, keçən vaxtı ölçmək üçün isə callback-ləri saymaq əvəzinə performance.now() istifadə et.
İtən rejection-lar
async function init() {
try {
loadConfig();
} catch (error) {
showError(error);
}
}loadConfig async funksiyadırsa, await unudulduğu üçün catch onun rejection-unu heç vaxt tutmur. Promise handler-siz rədd ediləndə brauzer mikrotapşırıq checkpoint-indən sonra onu yoxlayır və promise hələ də emal olunmayıbsa, sonrakı tapşırıqda window üzərində unhandledrejection hadisəsi göndərir. Node.js-də (v15-dən bəri) emal olunmamış rejection default olaraq prosesi çökdürür. catch-i (və ya try daxilində await-i) promise-i yaradan elə həmin sinxron kodda əlavə et.
Microtask starvation
The checkpoint drains the queue until it is empty, so a microtask that keeps queuing microtasks never lets the loop move on:
function loop() {
queueMicrotask(loop);
}
loop();The page freezes: no timers, no input handling, no rendering. A recursive promise chain does the same. The setTimeout version does not freeze the page, because each callback is a separate task and the browser can render and handle input between them.
Promises don't make code non-blocking
Wrapping heavy work in a promise does not move it off the main thread. The executor of new Promise(...) runs synchronously, and a then callback runs as a microtask — still before the next render. To stay responsive, split the work across tasks or move it to a Web Worker (see the Senior level).
Timers are not precise
- The delay is a minimum; a busy main thread postpones every timer.
- The HTML spec clamps nested timers: once
setTimeoutcalls are nested more than five levels deep, delays below 4 ms become 4 ms. - Browsers throttle timers in background tabs, and the exact rules differ between browsers.
Use requestAnimationFrame for animations and performance.now() to measure elapsed time instead of counting callbacks.
Lost rejections
async function init() {
try {
loadConfig();
} catch (error) {
showError(error);
}
}If loadConfig is async, the missing await means catch never sees its rejection. When a promise is rejected without a handler, the browser checks it after the microtask checkpoint and, if it is still unhandled, fires an unhandledrejection event on window in a later task. In Node.js (since v15) an unhandled rejection crashes the process by default. Attach catch (or await inside try) in the same synchronous code that creates the promise.
React və event loop
Avtomatik batching
set funksiyasını çağırmaq dərhal re-render-ə səbəb olmur — o, yeniləməni növbəyə qoyur. React yeniləmələri növbəyə qoyan kod (məsələn, hadisə handler-i) bitənə qədər gözləyir, sonra onları birlikdə, bir render-də emal edir. React 18-dən etibarən createRoot ilə bu yeniləmələrin haradan gəlməsindən asılı olmayaraq işləyir: React hadisə handler-ləri, setTimeout, promise-lər və ya native hadisə listener-ləri.
function handleClick() {
fetchUser().then((user) => {
setUser(user);
setLoading(false);
});
}Hər iki yeniləmə tək bir re-render yaradır. Lakin React istifadəçinin ayrı-ayrı, qəsdli hərəkətlərini birləşdirmir: iki klik ayrıca emal olunur. Onu da nəzərə al ki, setter-i çağırdıqdan dərhal sonra state-i oxusan, köhnə dəyəri alacaqsan, çünki yeni dəyər yalnız növbəti render-də mövcud olur.
flushSync: son çarə
Bəzən DOM növbəti sətir icra olunmamış yenilənməlidir — məsələn, yenicə əlavə etdiyin elementə scroll etmək üçün:
import { flushSync } from "react-dom";
function handleAdd(text: string) {
flushSync(() => {
setTodos((prev) => [...prev, text]);
});
listRef.current?.lastElementChild?.scrollIntoView();
}flushSync React-i yeniləmələri emal edib DOM-u sinxron yeniləməyə məcbur edir. react.dev onu nadir hallarda lazım olan alət adlandırır və xəbərdarlıq edir ki, o, performansa ciddi zərər vura və Suspense sərhədlərini fallback göstərməyə məcbur edə bilər.
Effect-lər və paint
Brauzer yalnız render addımında, cari JavaScript bitəndən sonra paint edir. İki effect hook-u arasındakı fərqi də məhz bu izah edir:
useLayoutEffectReact DOM-a commit edəndən sonra və brauzer ekranı yenidən çəkməzdən əvvəl işləyir. Onun kodu və içindən planlaşdırılan state yeniləmələri paint-i bloklayır, ona görə elementi ölçüb yerini dəyişmək mümkündür və istifadəçi titrəmə görmür. Ondan həddən artıq istifadə tətbiqi yavaşladır.useEffect: Effect istifadəçinin hərəkəti (interaction) nəticəsində yaranmayıbsa, React adətən əvvəlcə brauzerə paint etməyə imkan verir. Klik kimi interaction nəticəsində yaranıbsa, React onu paint-dən əvvəl də icra edə bilər. İşi paint-dən sonraya saxlamaq lazımdırsa (məsələn,alert()), react.devsetTimeoutistifadə etməyi təklif edir.
Automatic batching
Calling a set function does not re-render immediately — it queues an update. React waits until the code that queued the updates (an event handler, for example) has finished, and then processes them together in one render. Since React 18 with createRoot, this applies wherever the updates come from: React event handlers, setTimeout, promises or native event listeners.
function handleClick() {
fetchUser().then((user) => {
setUser(user);
setLoading(false);
});
}Both updates produce a single re-render. React does not batch across separate intentional events, though: two clicks are handled separately. Also note that reading state right after calling its setter still gives the old value, because the new value only exists in the next render.
flushSync: the escape hatch
Sometimes the DOM has to be up to date before the next line runs — for example, to scroll to an item you have just added:
import { flushSync } from "react-dom";
function handleAdd(text: string) {
flushSync(() => {
setTodos((prev) => [...prev, text]);
});
listRef.current?.lastElementChild?.scrollIntoView();
}flushSync forces React to process the updates and update the DOM synchronously. react.dev calls it uncommon and warns that it can significantly hurt performance and may force Suspense boundaries to show their fallback.
Effects and paint
The browser paints only in its rendering step, after the current JavaScript has finished. That explains the difference between the two effect hooks:
useLayoutEffectruns after React commits to the DOM and before the browser repaints. Its code and any state updates scheduled from it block the paint, so you can measure an element and reposition it without a visible flicker. Overusing it makes the app slow.useEffect: if the Effect was not caused by an interaction, React generally lets the browser paint first. If it was caused by an interaction such as a click, React may run it before paint. To defer work until after paint (for example, analert()), react.dev suggestssetTimeout.
Uzun işin planlaşdırılması, React scheduler-i və Node.js
Event loop-a növbə ver
İşləyən tapşırığı heç nə kəsə bilmir. Ona görə ağır iş zamanı səhifənin cavab verməyə davam etməsinin yeganə yolu işi könüllü dayandırıb yeni tapşırıqda davam etdirməkdir (buna yielding deyilir). Mikrotapşırıqla növbə vermək (await Promise.resolve()) kömək etmir: render və input mikrotapşırıq növbəsi boşalana qədər gözləyir.
function yieldToMain() {
if (globalThis.scheduler?.yield) {
return scheduler.yield();
}
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function processAll(items, handleItem) {
let sliceStart = performance.now();
for (const item of items) {
handleItem(item);
if (performance.now() - sliceStart > 10) {
await yieldToMain();
sliceStart = performance.now();
}
}
}scheduler.yield() davamı prioritetli tapşırıq kimi planlaşdırır, lakin MDN onu məhdud dəstəklənən (limited availability) API kimi qeyd edir, ona görə əvvəlcə mövcudluğunu yoxla. Hər hissəni 50 ms-lik long task həddindən xeyli aşağı saxla. Mənalı şəkildə bölünə bilməyən, CPU-nu yükləyən işin yeri Web Worker-dir — onun öz thread-i və event loop-u var.
React scheduler-i
React də eyni ideyanı tətbiq edir. Onun scheduler paketi işi makrotapşırıqlar şəklində icra edir — brauzerlərdə MessageChannel vasitəsilə; bu üsul iç-içə setTimeout-dan fərqli olaraq 4 ms-lik məhdudiyyətə tabe deyil. Concurrent render zamanı (startTransition, useDeferredValue) React iş vahidləri arasında bir neçə millisaniyəlik vaxt payının bitib-bitmədiyini yoxlayır; bitibsə, brauzerə növbə verir və işi yeni tapşırıqda davam etdirir. Transition render-ini daha təcili yeniləmə, məsələn, input-a mətn yazılması da kəsə bilər. DOM-a commit isə hissələrə bölünmür.
Node.js-dəki fərqlər
- Dövr libuv tərəfindən həyata keçirilir və fazalarla işləyir: timers → pending callbacks → poll (I/O) → check (
setImmediate) → close callbacks. process.nextTickcallback-lərinin öz növbəsi var. CommonJS kodunda və callback-lərin içində bu növbə promise mikrotapşırıqlarından əvvəl boşaldılır; ES modulun yuxarı səviyyəli kodunda isə əvvəlcə promise callback-ləri işləyir. Node.js sənədləri,nextTick-in xüsusi imkanları lazım deyilsə,queueMicrotaskistifadə etməyi tövsiyə edir.- Əsas moduldan çağırılanda
setTimeout(fn, 0)vəsetImmediate(fn)-in ardıcıllığı qeyri-müəyyəndir; I/O callback-inin içində isəsetImmediatehəmişə birinci işləyir. - Rekursiv
nextTickçağırışları I/O-nu "ac qoyur" (starvation) — eynilə rekursiv mikrotapşırıqların səhifəni dondurduğu kimi.
Yield to the event loop
Nothing can interrupt a running task, so the only way to stay responsive during heavy work is to stop voluntarily and continue in a new task. Yielding with a microtask (await Promise.resolve()) does not help: rendering and input wait until the microtask queue is empty.
function yieldToMain() {
if (globalThis.scheduler?.yield) {
return scheduler.yield();
}
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function processAll(items, handleItem) {
let sliceStart = performance.now();
for (const item of items) {
handleItem(item);
if (performance.now() - sliceStart > 10) {
await yieldToMain();
sliceStart = performance.now();
}
}
}scheduler.yield() schedules the continuation as a prioritized task, but MDN lists it as limited availability, so feature-detect it. Keep each slice well under the 50 ms long-task threshold. CPU-heavy work that can't be split sensibly belongs in a Web Worker, which has its own thread and event loop.
React's scheduler
React applies the same idea. Its scheduler package runs work as macrotasks — in browsers through MessageChannel, which, unlike nested setTimeout, is not clamped to 4 ms. During concurrent rendering (startTransition, useDeferredValue), React checks between units of work whether its time slice of a few milliseconds is used up and, if so, yields and continues in a new task. A transition render can also be interrupted by a more urgent update such as typing. The commit to the DOM is not split.
Node.js differences
- The loop is implemented by libuv and runs in phases: timers → pending callbacks → poll (I/O) → check (
setImmediate) → close callbacks. process.nextTickcallbacks have their own queue. In CommonJS code and inside callbacks it is drained before promise microtasks; in the top-level code of an ES module, promise callbacks run first. Node's docs recommendqueueMicrotaskunless you neednextTickspecifically.- From the main module, the order of
setTimeout(fn, 0)andsetImmediate(fn)is non-deterministic; inside an I/O callback,setImmediatealways runs first. - Recursive
nextTickcalls starve I/O, just as recursive microtasks freeze a page.
Müsahibə üçün tövsiyələr
İzahı strukturlaşdır
Cavabı aşağıdan yuxarı qur: bir thread və → host asinxron işi Web API-lər vasitəsilə görür → bitmiş iş tapşırıq kimi növbəyə düşür → hər tapşırıqdan sonra mikrotapşırıq növbəsi boşaldılır → brauzer render imkanı olanda render edir. Promise job-larını ECMAScript-in, event loop-u isə HTML spesifikasiyasının müəyyən etdiyini qeyd etsən, mövzunu dərindən bildiyini göstərərsən.
Output-u təxmin etmə sualları
Üç sütun saxla: çap olunanlar, mikrotapşırıq növbəsi, tapşırıq növbəsi.
- Bütün sinxron kodu icra et və hər sətrin nəyi növbəyə qoyduğunu qeyd et.
- Mikrotapşırıq növbəsini əvvəldən axıra boşalt. Bu zaman əlavə olunanlar növbənin sonuna düşür və elə həmin keçiddə icra olunur.
- Bir tapşırıq icra et, sonra mikrotapşırıqları yenidən boşalt. Təkrarla.
Klassik tələlərə diqqət et: ilk await-ə qədər olan kod sinxrondur; artıq resolve olunmuş promise-in then-i dərhal növbəyə düşür, zəncirdəki növbəti then isə yalnız əvvəlki callback bitəndə; hər taymer callback-i ayrıca tapşırıqdır.
Fərqləndirən detallar
- Real istifadəçi klikində eyni elementin iki listener-i arasında mikrotapşırıqlar icra olunur, çünki onların arasında call stack boşalır.
element.click()skriptdən çağırılanda isə stack boş olmur, ona görə əvvəl hər iki listener, sonra mikrotapşırıqlar işləyir. - Nəzəriyyəni praktika ilə əlaqələndir: long task-lar INP-ni pisləşdirir, ağır iş hissələrə bölünüb aralarda növbə verməlidir, React yeniləmələri batch edir,
useLayoutEffectisə paint-i bloklayır.
Qaçınmalı olduğun yanlış fikirlər
- "
setTimeout(fn, 0)dərhal icra olunur." - "Promise-lər başqa thread-də işləyir."
- "
asyncfunksiyanı paralel icra edir." - "Brauzer hər tapşırıqdan sonra ekranı yenidən çəkir."
Structure the explanation
Build the answer bottom-up: one thread and a → the host does asynchronous work through Web APIs → finished work is queued as tasks → after each task the microtask queue is drained → the browser renders when it has a rendering opportunity. Mentioning that ECMAScript defines promise jobs while the HTML spec defines the event loop shows depth.
Tracing output questions
Keep three columns: output, microtask queue, task queue.
- Run all synchronous code and note what each line queues.
- Drain the microtask queue front to back. Anything queued meanwhile goes to the end and runs in the same pass.
- Run one task, then drain the microtasks again. Repeat.
Watch for the classic traps: code before the first await is synchronous; then on an already-resolved promise is queued immediately, but a chained then is queued only when the previous callback finishes; every timer callback is its own task.
Details that stand out
- With a real user click, microtasks run between two listeners on the same element, because the call stack empties between them. With
element.click()called from a script, the stack is not empty, so both listeners run first and the microtasks after them. - Connect the theory to practice: long tasks hurt INP, heavy work should yield between chunks, React batches updates, and
useLayoutEffectblocks paint.
Misconceptions to avoid
- "
setTimeout(fn, 0)runs immediately." - "Promises run on another thread."
- "
asyncmakes a function run in parallel." - "The browser repaints after every task."
Kodu event loop baxımından review edərkən nəyi yoxlamalı
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. Bu yoxlamaları etməsən, kod bloklayıb klikləri və ekranın yenilənməsini ləngidə, ya da xətaları itirib callback-ləri heç kimin planlaşdırmadığı ardıcıllıqla icra edə bilər.
- Handler və ya dövr ağır işi bir dəfəyə görürmü? Tapşırıq icra olunduqca brauzer nə kliki emal edə, nə də paint edə bilir. Əməliyyatı DevTools-un Performance panelində record et — panel long task-ları qırmızı üçbucaqla işarələyir; işin
setTimeoutvə yascheduler.yield()ilə növbə verən hissələrə bölünməsini, ya da Web Worker-ə köçürülməsini gözlə. - Kod promise-in və ya
async-in işi thread-dən kənara çıxardığını güman edirmi?new Promise-in executor-u sinxron icra olunur,thencallback-ləri isə növbəti render-dən əvvəl kimi işləyir. Ona görə dəawait Promise.resolve()nə paint-ə, nə də input-a yol açır. tryiçindəki hər async çağırışawaitilə gözlənilirmi?awaitolmasa,catchrejection-u heç vaxt görmür: brauzerunhandledrejectionhadisəsi göndərir, Node.js isə (v15-dən bəri) default olaraq prosesi dayandırır.- Mikrotapşırıq özünü yenidən növbəyə qoya bilirmi? Özünü durmadan yenidən planlaşdıran
queueMicrotaskvə ya promise zənciri event loop-un taymerlərə, input-a və render-ə keçməsinə heç vaxt imkan vermir və səhifə donur. Təkrarlanan işin yerisetTimeout-dur: o, brauzerə arada render etməyə imkan verir. - Kod taymerin dəqiq gecikməsinə arxalanırmı? Gecikmə minimumdur: məşğul thread callback-i təxirə salır, fon tablarında isə brauzer taymerləri yavaşladır. Keçən vaxtı callback-ləri saymaqla yox,
performance.now()ilə ölç. - Animasiyalar
requestAnimationFrameilə qurulubmu? Taymer dövrləri kadrlarla uzlaşmır: iki kadr arasında iki dəfə işləyə və ya bir kadrı ötürə bilər. isə hər kadrda bir dəfə, stil və layout hesablanmazdan dərhal əvvəl işləyir.
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. Skip it and the code can block the , so clicks and repaints wait, or lose errors and run callbacks in an order nobody planned.
- Does a handler or loop do heavy work in one go? While a task runs, the browser can neither handle a click nor paint. Record it in the DevTools Performance panel, which marks long tasks with a red triangle; expect chunks that yield with
setTimeoutorscheduler.yield(), or a Web Worker. - Does the code assume that a promise or
asyncmoves work off the thread? Thenew Promiseexecutor runs synchronously, andthencallbacks run as before the next render, soawait Promise.resolve()lets neither paint nor input through. - Is every async call inside
tryawaited? Withoutawait,catchnever sees the rejection: the browser firesunhandledrejection, and Node.js (since v15) ends the process by default. - Can a microtask queue itself again? A
queueMicrotaskor promise chain that keeps rescheduling itself never lets the loop reach timers, input or rendering, and the page freezes. Repeating work belongs insetTimeout, which lets the browser render in between. - Does the code rely on a timer's exact delay? The delay is a minimum: a busy thread postpones the callback, and background tabs throttle timers. Measure elapsed time with
performance.now(), not by counting callbacks. - Do animations use
requestAnimationFrame? Timer loops are not aligned with frames: they can run twice between frames or miss one. runs once per frame, right before style and layout.
Özünü yoxla
Təcrübədə sına
Bu mövzudan istifadə edən praktiki işlər.
İnsident simulyatoru
Sistem dizaynı
Real kodda gör
Buna əsaslanan real kitabxanaların mənbə kodu üzrə bələdçili turlar.