Created
August 8, 2013 11:07
-
-
Save floz/6183741 to your computer and use it in GitHub Desktop.
CoffeeScript - RequestAnimationFrame
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
do -> | |
w = window | |
for vendor in ['ms', 'moz', 'webkit', 'o'] | |
break if w.requestAnimationFrame | |
w.requestAnimationFrame = w["#{vendor}RequestAnimationFrame"] | |
w.cancelAnimationFrame = (w["#{vendor}CancelAnimationFrame"] or | |
w["#{vendor}CancelRequestAnimationFrame"]) | |
# deal with the case where rAF is built in but cAF is not. | |
if w.requestAnimationFrame | |
return if w.cancelAnimationFrame | |
browserRaf = w.requestAnimationFrame | |
canceled = {} | |
w.requestAnimationFrame = (callback) -> | |
id = browserRaf (time) -> | |
if id of canceled then delete canceled[id] | |
else callback time | |
w.cancelAnimationFrame = (id) -> canceled[id] = true | |
# handle legacy browsers which don’t implement rAF | |
else | |
targetTime = 0 | |
w.requestAnimationFrame = (callback) -> | |
targetTime = Math.max targetTime + 16, currentTime = +new Date | |
w.setTimeout (-> callback +new Date), targetTime - currentTime | |
w.cancelAnimationFrame = (id) -> clearTimeout id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment