Last active
August 29, 2015 14:17
-
-
Save nekoneko-wanwan/9f6db53ef42f8cee96a1 to your computer and use it in GitHub Desktop.
requestAnimFrameの実装サンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
なお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
なおscrollイベントの間引きについては、以下が参考になった
scrollイベントが呼ばれすぎることへの対処
http://javascripter.hatenablog.com/entry/2014/10/03/212017