Javascript Animation 관련

2017. 7. 26. 15:08프로그래밍/Jscript

setInterval  vs requestAnimationFrame 

30 Frame으로 제어할 경우 테스트 중에 오류가 있었음을 .. 흠..


<!DOCTYPE html>

<html lang='kr'>

<head>

<meta charset="utf-8">

</head>

<body>


<div id="x">1</div>

<div id="x2">1</div>

<Script>


var cnt = 0,cnt2=0;

var t = document.getElementById("x");

var t2 = document.getElementById("x2");


function ct(cnt){

return parseFloat(cnt/30);

}

   function timeUpdate2(){

       //calculate difference since last repaint

        t2.innerHTML  =ct(cnt2) ;

cnt2++;

   }


   var Timer = function(callback, fps){

 var now = 0;

 var delta = 0;

 var then = Date.now();


 var frames = 0;

 var oldtime = 0;

 var req_id  = "";


 fps = 1000 / ( fps || this.fps || 60);


 this.stop = function(){

  window.cancelAnimationFrame(req_id);

 }


 return requestAnimationFrame( function loop(time){

   req_id = requestAnimationFrame(loop);


   now = Date.now();

   delta = now - then;


   if (delta > fps) {

     // Update time stuffs

     then = now - (delta % fps);


     // Calculate the frames per second.

     frames = 1000 / (time - oldtime)

     oldtime = time;


     // Call the callback-function and pass

     // our current frame into it.

     callback(frames);

   }

 });

};

var set = true;


  setInterval(timeUpdate2, 1000 / 30);

  

   var x= Timer(function(fps){

  t.innerHTML  =ct(cnt) ;

cnt++;

},30);

</Script>



</body>


</html>


위와 같은 코드를 만들고 수행 하였을 경우


setInterval 부분은 속도가 빨라지는 경우가 보여진다. 

실제 30frame === 1s 로는 requestAnimationFrame 사용하는게 맞다..


그러나 두둥.. 문제 점

에니메이션을 만드로 두개를 수행 할 경우 Active 된 브라우져에서는 제대로 작동 하지만. 

Active 아닐 경우는 Setinterval는 안보이는 곳에서도 동작을 하고 requestAnimationFrame  경우는 동작하지 않는 모습을 볼수 있다.


과연 어느것을 사용해야하는 것인가.?