Skip to content

Instantly share code, notes, and snippets.

@nekoneko-wanwan
Last active August 29, 2015 14:17
Show Gist options
  • Save nekoneko-wanwan/9f6db53ef42f8cee96a1 to your computer and use it in GitHub Desktop.
Save nekoneko-wanwan/9f6db53ef42f8cee96a1 to your computer and use it in GitHub Desktop.
requestAnimFrameの実装サンプル
// fallback
window.requestAnimFrame = (function() {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, time) {
var time = time ? time: 1000 / 60;
window.setTimeout(callback, time);
}
);
})();
/* cancelAnimationFrame fallback */
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
var i = 0;
function tick(){
if (i < 100) {
i++;
cl(i, 'hoge');
requestAnimationFrame(tick);
}
}
function cl(num, str) {
console.log(num + ' ' + str);
}
tick();
// -----------------------------
var anim = function() {
console.log('fuga');
// 第2引数は、setTimeoutの場合のみ使われる
requestAnimFrame(anim, 1000 / 1);
};
anim();
@nekoneko-wanwan
Copy link
Author

なおscrollイベントの間引きについては、以下が参考になった

scrollイベントが呼ばれすぎることへの対処
http://javascripter.hatenablog.com/entry/2014/10/03/212017

結論から言うと、スクロールと画面の同期遅れを最小限にしたい場合はsetTimeoutではなくrequestAnimationを使ったほうがsetTimeout(fn, 0)より良くて、画面のチラツキが気にならないような場面ではsetTimeout(fn, 100)くらいを使うと良いと思う。

@nekoneko-wanwan
Copy link
Author

なおrequestAnimationFrameはグローバルなので、使い方によってはthisがwindowになってしまい動作しないので注意

render: function() {
    this.updatePosition();
    this.draw();
    requestAnimationFrame(this.render.bind(this));  // thisをbindしてやる
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment