---
id: wiki-2026-0508-브라우저-메인-스레드-최적화-및-타임-슬라이싱
title: 브라우저 메인 스레드 최적화 및 타임 슬라이싱
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Main Thread Optimization, Time Slicing, INP Optimization, Long Tasks, Scheduler API]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [web-performance, main-thread, scheduler, inp, long-tasks, web-workers]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: typescript
  framework: vanilla-web-platform
---

# 브라우저 메인 스레드 최적화 및 타임 슬라이싱

## 매 한 줄
> **"매 long task 를 매 50ms 미만 chunk 로 split, scheduler.yield() 로 매 input 에 양보"**. 매 INP (Interaction to Next Paint, 2024 부터 Core Web Vital) 의 핵심 metric — 매 200ms 이하 가 Good. 매 2026 의 Scheduler API + isInputPending + Web Worker 의 매 standard toolkit.

## 매 핵심

### 매 Main thread 의 책임
- **JS execution**, Style + Layout + Paint, Compositing prep, Event dispatch.
- **Long task**: 50ms 초과 task — INP 의 적.
- **Render-blocking**: long task 동안 rAF, input handler 모두 starve.

### 매 Time slicing 전략
- **Yield to event loop**: scheduler.yield() (2026 baseline), 매 fallback 으로 setTimeout(0).
- **Priority-aware scheduling**: scheduler.postTask({priority: 'background'}).
- **isInputPending()**: input 의 pending 시 매 즉시 yield.
- **Web Worker offload**: pure compute (parsing, encoding, crypto) 는 main thread 떠남.

### 매 응용
1. **Large list rendering**: virtualized + chunked.
2. **JSON parsing / encoding**: Worker + Transferable.
3. **Hydration**: priority-based React 19 / Astro / Qwik resumability.

## 💻 패턴

### scheduler.yield() (2026 baseline)
```typescript
async function processChunks(items: Item[]) {
  for (const it of items) {
    process(it);
    if (navigator.scheduling?.isInputPending?.()) {
      await scheduler.yield(); // resume after input is handled
    }
  }
}
```

### scheduler.postTask with priority
```typescript
// User-blocking: must run ASAP
scheduler.postTask(updateUserCriticalUI, { priority: 'user-blocking' });
// User-visible: default
scheduler.postTask(refreshSidebar, { priority: 'user-visible' });
// Background: prefetch, analytics flush
scheduler.postTask(prefetchNext, { priority: 'background' });
```

### Manual time slicer (fallback)
```typescript
async function timeSlice<T>(items: T[], work: (item: T) => void, budgetMs = 5) {
  let start = performance.now();
  for (const it of items) {
    work(it);
    if (performance.now() - start > budgetMs) {
      await new Promise<void>((r) => setTimeout(r, 0));
      start = performance.now();
    }
  }
}
```

### Web Worker offload (Comlink pattern)
```typescript
// worker.ts
import * as Comlink from 'comlink';
const api = {
  parseLargeJSON: (text: string) => JSON.parse(text),
  hashFile: async (buf: ArrayBuffer) => {
    const h = await crypto.subtle.digest('SHA-256', buf);
    return new Uint8Array(h);
  },
};
Comlink.expose(api);

// main.ts
const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
const api = Comlink.wrap<typeof api>(worker);
const parsed = await api.parseLargeJSON(hugeText);
```

### Transferable ArrayBuffer (zero-copy)
```typescript
const buf = new ArrayBuffer(1024 * 1024 * 10);
worker.postMessage({ buf }, [buf]); // ownership transfers; main no longer holds
```

### INP measurement (Performance Observer)
```typescript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries() as PerformanceEventTiming[]) {
    const inp = entry.processingEnd - entry.startTime;
    if (inp > 200) console.warn('Slow interaction', entry.name, inp);
  }
});
observer.observe({ type: 'event', buffered: true, durationThreshold: 16 });
```

### React 19 — useTransition for non-urgent updates
```typescript
const [isPending, startTransition] = useTransition();

function handleSearch(q: string) {
  setQuery(q); // urgent — input echo
  startTransition(() => {
    setSearchResults(filterHugeList(allItems, q)); // non-urgent — yields to input
  });
}
```

### IntersectionObserver — lazy heavy work
```typescript
const io = new IntersectionObserver((entries) => {
  for (const e of entries) {
    if (e.isIntersecting) {
      scheduler.postTask(() => mountHeavyComponent(e.target), { priority: 'background' });
      io.unobserve(e.target);
    }
  }
}, { rootMargin: '200px' });
document.querySelectorAll('.lazy-section').forEach(el => io.observe(el));
```

### Long Animation Frames (LoAF) API
```typescript
new PerformanceObserver((list) => {
  for (const e of list.getEntries() as any[]) {
    console.warn('LoAF', e.duration, e.scripts);
  }
}).observe({ type: 'long-animation-frame', buffered: true });
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| > 50ms synchronous work | Time slice with scheduler.yield() |
| Pure compute (parse, hash, image) | Web Worker + Transferable |
| Non-urgent state update (React) | useTransition |
| Off-screen heavy work | IntersectionObserver + postTask |
| Background prefetch | scheduler.postTask priority 'background' |
| Hot UI update with input | isInputPending checkpoint |

**기본값**: 매 task > 5ms 면 yield consider. 매 task > 50ms 면 split mandatory. 매 pure compute 는 Worker 의 first choice.

## 🔗 Graph
- 부모: [[Web-Performance]] · [[Core-Web-Vitals]] · [[INP-Optimization]]
- 변형: [[Scheduler-API]] · [[Web-Workers]] · [[OffscreenCanvas]]
- 응용: [[성능 중심의 웹 애니메이션 및 인터랙션 구현]] · [[Virtualized-Lists]] · [[React-Concurrent-Features]]
- Adjacent: [[Long-Tasks-API]] · [[Long-Animation-Frames]] · [[Comlink]]

## 🤖 LLM 활용
**언제**: time-slice boilerplate, Worker setup scaffold, scheduler API migration plan.
**언제 X**: 매 actual INP 측정 — RUM (CrUX, Web Vitals JS) 만 truth. LLM 의 perf claim 의 hallucination.

## ❌ 안티패턴
- **Sync heavy work in input handler**: 매 INP 폭증.
- **setTimeout(0) busy-loop**: scheduler.yield() preferred (priority-aware).
- **Worker per task spawn**: 매 startup overhead. Pool 또는 long-lived worker.
- **structuredClone of huge data to Worker**: Transferable 사용.
- **Ignoring isInputPending**: 매 yield 의 timing 의 너무 늦음.

## 🧪 검증 / 중복
- Verified (web.dev/inp 2026, Scheduler API spec, LoAF spec, Chrome DevTools Performance docs).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Scheduler API, time slicing, Worker offload, INP patterns |
