Microtasks versus tasks

마이크로태스크와 태스크

Promise callbacks run after the current task and before the next timer task.

···
html
<div class="v"><header>QUEUE ORDER <span>A → B → C</span></header><div class="stage queue"><div class="lanes"><div>script <b>A</b></div><div>Promise <b>B</b></div><div>timer <b>C</b></div></div><div class="console">output: <span id="out"></span><i id="cursor"></i></div></div><div class="muted">microtasks drain before next task</div></div>
css
.v{width:min(94vw,760px);height:min(88vh,320px);padding:clamp(9px,2.4vmin,18px);border:1px solid var(--line);border-radius:12px;background:var(--surface);font:500 clamp(12px,2.4vmin,16px)/1.3 var(--font-sans,system-ui,sans-serif);display:flex;flex-direction:column;gap:clamp(5px,1.4vmin,10px);overflow:hidden}.v header{display:flex;align-items:center;justify-content:space-between;gap:8px;color:var(--accent);font-weight:700}.v header span{color:var(--muted);font-weight:500}.v .stage{flex:1;min-height:0;position:relative}.v .muted{color:var(--muted)}.v .active{background:color-mix(in srgb,var(--accent) 18%,var(--surface));border-color:var(--accent)!important;color:var(--fg)}.v button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:7px;padding:5px 8px;cursor:pointer}.queue{display:flex;flex-direction:column;justify-content:center;gap:10px}.lanes{display:flex;gap:6px}.lanes div{flex:1;min-width:0;padding:7px 3px;text-align:center;border:1px solid var(--line);border-radius:7px;background:var(--bg)}.lanes b{color:var(--accent)}.console{padding:9px;background:var(--bg);border-left:3px solid var(--accent);font-family:ui-monospace,monospace}.console i{display:inline-block;width:7px;height:1em;background:var(--accent);vertical-align:middle;animation:blink .6s steps(1) infinite}@keyframes blink{50%{opacity:0}}
js
let i=0;function tick(){document.getElementById("out").textContent="A B C".slice(0,[1,3,5][i]);i=(i+1)%3}tick();setInterval(tick,750)

Timer callbacks go to the task queue; Promise reactions go to the microtask queue. Once the current script ends, the browser drains microtasks before the next task.

The demo prints `A`, Promise `B`, then timer `C`. A chain that continually creates microtasks can delay later tasks and rendering.

When to use

Check queue ordering when asynchronous callbacks run in a surprising order.

Open as page ↗