재우니의 블로그

 

 

requestAnimationFrame 함수를 지원하기 전에는 setInterval 함수를 이용하여, 애니메이션을 위해 매끄럽게 보이기 위하여  초당 60 개의 "프레임" 이므로 다음과 같이 반복하여 실행합니다. 

setInterval(function() {
  // animiate something
}, 1000/60);

 

requestAnimationFrame 함수는 위의 setInterval 함수보다 좋은 장점은 브라우저에서 최적화 할 수 있으므로 애니메이션이 더 부드러워집니다.

 

 

단, requestAnimationFrame 함수는 ie 9 이하에서는 작동이 되지 않습니다.

 

caniuse.com/requestanimationframe

 

Can I use... Support tables for HTML5, CSS3, etc

API allowing a more efficient way of running script-based animation, compared to traditional methods using timeouts. Also covers support for cancelAnimationFrame

caniuse.com

 

이를 위해서 지원하지 않은 브라우저를 위해 setTimeout 으로 구현한 polyfill 함수를 제공해 주고 있습니다.

 

gist.github.com/paulirish/1579671

 

requestAnimationFrame polyfill

requestAnimationFrame polyfill. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

전체적인 소스는 아래와 같습니다. 테스트 한 결과 ie 8 에서 잘 작동하네요.

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        .outside {
            position: relative;
            background-color: #ff0eef;
            width: 100px;
        }
    </style>

    <script>
        (function requestAnimationFrame_polyfill() {
            var lastTime = 0;
            var vendors = ['webkit', 'moz', 'ms', 'o'];
            for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
                window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
                window.cancelAnimationFrame =
                    window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
            }

            if (!window.requestAnimationFrame)
                window.requestAnimationFrame = function (callback, element) {
                    var currTime = new Date().getTime();
                    var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                    var id = window.setTimeout(function () { callback(currTime + timeToCall); },
                        timeToCall);
                    lastTime = currTime + timeToCall;
                    return id;
                };

            if (!window.cancelAnimationFrame)
                window.cancelAnimationFrame = function (id) {
                    clearTimeout(id);
                };
        }())
    </script>
</head>

<body>

    <div class="outside">내 최애 과일은..</div>

    <script>
        var count = 0;
        var el = document.querySelector(".outside");
        el.style.left = "0px"; //default값으로 설정

        function run() {
            if (count > 40) { //count가 40을 넘으면 return
                return
            }
            count += 2 //  2px씩 증가. 
            el.style.left = parseInt(el.style.left) + count + "px";
            console.log(el.style.left);
            requestAnimationFrame(run);
            // reqeustAnimationFrame()함수를 통해서 원하는 함수를 인자로 넣어준다.
            // 브라우저는 인자로 받은 그 비동기 함수가 실행될 적절한 타이밍에 실행시켜줌.
        }
        requestAnimationFrame(run);

    </script>

</body>

</html>

 

참고사이트 

 

css-tricks.com/using-requestanimationframe/

 

Using requestAnimationFrame | CSS-Tricks

There used to be just one way to do a timed loop in JavaScript: setInterval(). If you needed to repeat something pretty fast (but not

css-tricks.com