在瀏覽器動畫程序中,咱們一般使用一個定時器來循環每隔幾毫秒移動目標物體一次,來讓它動起來。現在有一個好消息,瀏覽器開發商們決定:「嗨,爲何咱們不在瀏覽器裏提供這樣一個API呢,這樣一來咱們能夠爲用戶優化他們的動畫。」因此,這個requestAnimationFrame()
函數就是針對動畫效果的API,你能夠把它用在DOM上的風格變化或畫布動畫或WebGL中。javascript
瀏覽器能夠優化並行的動畫動做,更合理的從新排列動做序列,並把可以合併的動做放在一個渲染週期內完成,從而呈現出更流暢的動畫效果。好比,經過requestAnimationFrame()
,JS動畫可以和CSS動畫/變換或SVG SMIL動畫同步發生。另外,若是在一個瀏覽器標籤頁裏運行一個動畫,當這個標籤頁不可見時,瀏覽器會暫停它,這會減小CPU,內存的壓力,節省電池電量。java
// shim layer with setTimeout fallback window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); // usage: // instead of setInterval(render, 16) .... (function animloop(){ requestAnimFrame(animloop); render(); })(); // place the rAF *before* the render() to assure as close to // 60fps with the setTimeout fallback.
實現0到100的輸出 requestAnimationFrame實現web
(function(){ var i=0; var timer=requestAnimationFrame(function fn() { console.log(i++); timer=requestAnimationFrame(fn); if(i>100){ cancelAnimationFrame(timer); } }) }())
setTimeout實現瀏覽器
(function setTime(){ var i=0; var timer = setTimeout(function fn() { console.log(i++); timer=setTimeout(fn,1000/60); if(i>100){ clearTimeout(timer) } },1000/60) }())
setInterval實現函數
(function() { var i=0; var timer = setInterval(function () { console.log(i++); if(i>100){ clearInterval(timer); } },1000/60) }())