Develop/canvas

34. requestAnimationFrame() - setInterval()과 동일

GuriZzang 2015. 8. 10. 15:36

GuriZzang.com에 오시면 

더 자세한 내용을 보실 수 있습니다.


Syntax

window.requestAnimationFrame(callback);

Parameters

callback
A parameter specifying a function to call when it's time to update your animation for the next repaint. The callback has one single argument, a DOMHighResTimeStamp, which indicates the current time (the time returned from window.performance.now() ) for when requestAnimationFrame starts to fire callbacks.

Return value

long integer value, the request id, that uniquely identifies the entry in the callback list. This is a non-zero value, but you may not make any other assumptions about its value. You can pass this value towindow.cancelAnimationFrame() to cancel the refresh callback request.


기본적인 setInterval()과 비슷한 함수 입니다. 함수 호출은 밀리세컨드 단위로 호출됩니다.

인자로 함수를 받으며 방법은 아래와 같습니다.


추가 : callback 함수를 실행할때 timestamp 인자를 사용할 수 있습니다.



Source 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="/_include/Lib/jquery/jquery-2.1.4.min.js"></script>
    <style>
        html, body {height:100%; width:100%; padding:0px; margin:0px;}
        #move {display:inline-block; position:relative; background-color:red; width:100px; height:100px;}
    </style>
    <script>
        window.onload = init();
 
        var start = null;
        var element = null;
         
        function init(){
            window.requestAnimationFrame(step);
        }
         
        function step( timestamp ) {
            element = document.getElementById("move");
            if (!start) start = timestamp;
            var progress = timestamp - start;
             
            if( progress > 2000 ){
                start = timestamp;
            }
            element.style.left = Math.min(progress/10, 200) + "px";
            window.requestAnimationFrame(step);
        }
         
    </script>
</head>
<body>
 
<span id="move">aa</span>
 
</body>
</html>



Demo