Skip to content

Instantly share code, notes, and snippets.

@frostney
Last active December 17, 2015 23:19
Show Gist options
  • Save frostney/5688215 to your computer and use it in GitHub Desktop.
Save frostney/5688215 to your computer and use it in GitHub Desktop.
RequestAnimationFrame and CancelAnimationFrame as AMD modules (CoffeeScript edition)
do ->
vendors = ['ms', 'moz', 'webkit', 'o']
define 'requestAnimationFrame', ['root'], (root) ->
lastTime = 0
{requestAnimationFrame} = root
unless requestAnimationFrame
for x in vendors
requestAnimationFrame = root["#{x}RequestAnimationFrame"]
break if requestAnimationFrame
unless requestAnimationFrame
requestAnimationFrame = (callback, element) ->
currTime = Date.now()
timeToCall = Math.max 0, 16 - (currTime - lastTime)
id = root.setTimeout((-> callback(currTime + timeToCall)), timeToCall)
lastTime = currTime + timeToCall
id
requestAnimationFrame
define 'cancelAnimationFrame', ['root'], (root) ->
{cancelAnimationFrame} = root
unless cancelAnimationFrame
for x in vendors
cancelAnimationFrame = root["#{x}CancelAnimationFrame"] or root["#{x}CancelRequestAnimationFrame"]
break if cancelAnimationFrame
unless cancelAnimationFrame
cancelAnimationFrame = (id) -> root.clearTimeout id
cancelAnimationFrame
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment