본문 바로가기

Javascript Concepts

RequestAnimationFrame

requestAnimationFrame()


Syntax

window.requestAnimationFrame(callback);
  • requestAnimationFrame() 함수를 통해 다음 리페인트 전에 실행할 애니메이션 업데이트 함수를 등록할 수 있다.
  • 대부분의 웹 브라우저에서 콜백함수는 디스플레이의 refresh rate 에 맞춰 실행된다. (보통 1초에 60번)
  • 브라우저 탭이 백그라운드에서 실행중이거나 숨겨진 iframe에서 실행중일 때는 requestAnimationFrame() 호출이 일지 정지된다.
  • 콜백 함수는 현재시간을 의미하는 DOMHighResTimeStamp 라는 인자 하나를 넘겨 받는다. 만약 여러 개의 콜백이 큐에 쌓여 있어서 하나의 프레임 안에서 실행된다면, 각 콜백은 같은 타임스탬프를 인자로 받는다.

Example

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="progress" style="position: absolute; width:50px; height: 50px; background-color: orange;"></div>
</body>
<script>
let start = null;
const element = document.getElementById('progress');

function step(timestamp) {
  if (!start) start = timestamp;
  console.log("here")
  const progress = timestamp - start;
  element.style.left = Math.min(progress / 10, 200) + 'px';
  if (progress < 2000) { // Stop the animation after 2 seconds
    previousTimestamp = timestamp;
    window.requestAnimationFrame(step);
  }
}

window.requestAnimationFrame(step);

</script>
</html>

 

위와 같은 html 파일을 실행시켜보자. 애니메이션이 약 2초간 실행된 후 멈추는 것을 확인할 수 있다. 또한 브라우저 콘솔창을 확인해보면 "here" 이 약 120번 출력되었을 것이다.

setInterval() vs requestAnimationFrame()


브라우저에서 애니메이션을 나타내기 위해 setInterval() 함수를 통해 특정 시간마다 프레임을 새로 그려주는 함수를 실행시키는 방법도 있다. 그러나 이 방법은 그다지 권장되지 않는 방법이다. 사용자가 애니메이션을 '매끄럽게' 보기 위해서는 60FPS 의 속도로 실행되어야 한다. 즉, 다음 프레임이 누락되거나 조금 늦어질 경우 사용자는 애니메이션이 버벅거린다고 느낀다는 것이다.

60FPS = 60 frames per second = 16 ms per frame 

https://miro.medium.com/max/700/1*KmOiKHbzv0ZiDZzfe0CPLg.png

 

setTimeout() 이나 setInterval() 의 경우 콜백함수가 프레임에서 특정 시점(종료 시)에 실행되고, 종종 프레임이 누락되어 버벅거림 현상이 발생할 수 있기 때문에 requestAnimationFrame() 을 사용하는 것을 권장하고 있다고 한다.

 


Reference

'Javascript Concepts' 카테고리의 다른 글

Message Queue and Event Loop  (0) 2021.10.05
IIFE  (0) 2021.10.01
Scope  (0) 2021.09.28
ES Modules  (0) 2021.09.27