APM(ApachePhpMysql)

Promise.then() vs requestAnimationFrame()

DGeon 2025. 3. 19. 10:44
Promise.then() vs requestAnimationFrame()

Promise.then() vs requestAnimationFrame()

Promise.then()requestAnimationFrame()은 모두 비동기적으로 실행되지만, 수행되는 시점이 다릅니다.

🔹 실행 시점 비교

  • Promise.then() → 현재 실행 중인 코드가 끝난 바로 다음 (Microtask Queue)
  • requestAnimationFrame() → 브라우저가 다음 화면을 렌더링하기 직전 (Render Frame)

🔹 실행 순서 예제

console.log("1. 실행 시작");

Promise.resolve().then(() => {
    console.log("2. Promise.then() 실행");
});

requestAnimationFrame(() => {
    console.log("3. requestAnimationFrame() 실행");
});

console.log("4. 실행 완료");

🔹 예상 결과 (콘솔 출력 순서)

1. 실행 시작
4. 실행 완료
2. Promise.then() 실행
3. requestAnimationFrame() 실행

✅ 결론

  • Promise.then() → 현재 실행 중인 코드가 모두 끝난 직후 실행됨 (Microtask Queue)
  • requestAnimationFrame() → 브라우저가 다음 프레임을 렌더링하기 직전에 실행됨 (최적화된 UI 업데이트)
  • UI 변경이 끝난 후 실행하려면 requestAnimationFrame()을 사용하는 것이 적절함
  • 렌더링이 끝난뒤 사용 하는 것으로는 requestAnimationFrame 방법을 사용하고 비동기를 수행 후 또 다시 비동기를 수행해야 할때는 Promise.then 사용