Files
2nd/10_Wiki/Topics/AI_and_ML/Long Tasks.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

5.3 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-long-tasks Long Tasks API 10_Wiki/Topics verified self
Long Tasks
Long Animation Frame
LoAF
Main Thread Blocking
none A 0.9 applied
web-perf
performance-api
inp
main-thread
browser
2026-05-10 pending
language framework
JavaScript PerformanceObserver

Long Tasks API

매 한 줄

"매 long task = main thread 50ms+ 블록". INP/Responsiveness의 직접 원인. PerformanceObserver로 측정·attribute한다.

매 핵심

매 정의

  • Long Task: 단일 task가 50ms 초과로 main thread 점유.
  • 사용자 입력·rendering 지연 → INP 악화.
  • W3C spec: longtask PerformanceEntry.

매 후속 표준 (LoAF)

  • Long Animation Frame (Long Animation Frames API): frame 단위, attribution 강화.
  • entryType long-animation-frame — script source, style/layout 시간 포함.
  • Long Tasks API보다 정확하고 디버깅 친화적 (2024+).

매 측정 항목

  • duration, startTime
  • attribution (Long Tasks): TaskAttributionTiming, container 정도만 (cross-origin 익명화)
  • scripts[] (LoAF): name, sourceURL, function, invoker, executionStart/forcedStyleAndLayoutDuration

매 흔한 원인

  1. 큰 JS 번들 parse/compile
  2. 동기 layout/style (forced reflow)
  3. 무거운 React render (큰 리스트, memo 부재)
  4. JSON parse 큰 payload
  5. 동기 third-party script
  6. Hydration burst (Next.js, Nuxt)

매 완화

  • Code split, dynamic import
  • requestIdleCallback, scheduler.postTask, scheduler.yield()
  • Web Worker로 오프로드
  • Virtualization (큰 리스트)
  • React: Suspense, useDeferredValue, transitions
  • Defer non-critical scripts, async chunks

💻 패턴

Long Tasks 관찰

const obs = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log("long task", entry.duration, entry.name, entry.attribution);
  }
});
obs.observe({ type: "longtask", buffered: true });

Long Animation Frame (현대)

const obs = new PerformanceObserver((list) => {
  for (const e of list.getEntries()) {
    if (e.duration < 50) continue;
    for (const s of e.scripts) {
      console.log("LoAF script", s.name, s.sourceURL,
        s.duration, "fwd-layout:", s.forcedStyleAndLayoutDuration);
    }
  }
});
obs.observe({ type: "long-animation-frame", buffered: true });

scheduler.yield (cooperative)

async function processItems(items) {
  for (const item of items) {
    doWork(item);
    if (navigator.scheduling?.isInputPending?.() || performance.now() - last > 5) {
      await scheduler.yield();      // chunk 양보
      last = performance.now();
    }
  }
}

requestIdleCallback fallback

function chunked(items, fn) {
  let i = 0;
  function run(deadline) {
    while (i < items.length && deadline.timeRemaining() > 0) fn(items[i++]);
    if (i < items.length) requestIdleCallback(run);
  }
  requestIdleCallback(run);
}

Web Worker로 오프로드

// main
const w = new Worker("./parse.worker.js", { type: "module" });
w.postMessage(largePayload);
w.onmessage = (e) => render(e.data);

// parse.worker.js
self.onmessage = (e) => {
  const result = heavyParse(e.data);
  self.postMessage(result);
};

React deferred / transition

import { useDeferredValue, useTransition } from "react";
const deferred = useDeferredValue(query);
const [isPending, start] = useTransition();
start(() => setFilter(next));      // non-urgent → no long task on type

web-vitals 통합

import { onINP } from "web-vitals/attribution";
onINP((m) => {
  // m.attribution.longAnimationFrameEntries → 원인 frame
  beacon("inp", m);
}, { reportAllChanges: true });

매 결정 기준

상황 도구
측정 시작 LoAF (지원) → Long Tasks fallback
사용자 INP 추적 web-vitals attribution
CPU-bound Web Worker
큰 리스트 처리 scheduler.yield, chunking
Render bottleneck useDeferredValue, virtualization
Third-party 무거움 defer/async, Partytown

기본값: web-vitals onINP + LoAF observer로 attribute → 가장 큰 script 우선 최적화.

🔗 Graph

🤖 LLM 활용

언제: PerformanceObserver 코드, 원인 분류, 완화 전략 매핑. 언제 X: 실제 attribution은 production trace로 검증해야 정확.

안티패턴

  • 50ms threshold만 보고 47ms task 무시 (LoAF가 누적 표시)
  • requestAnimationFrame 안에 무거운 sync 작업
  • Worker로 보내고 직렬화 cost > 작업 cost
  • setTimeout(fn, 0)으로 yield (실제 양보 부족) → scheduler.yield
  • Long task 발생만 알리고 attribution 안 봄 → 원인 파악 불가
  • DevTools만 보고 production 측정 누락

🧪 검증 / 중복

  • Verified (W3C Long Tasks, web.dev INP, Long Animation Frames API). 신뢰도 A.
  • 중복: 없음.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — LoAF, scheduler.yield, web-vitals 통합