avocado-old/packages/timing/animation-frame.coffee
2019-03-17 23:45:48 -05:00

55 lines
1.2 KiB
CoffeeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Adapted from https://gist.github.com/paulirish/1579671#gistcomment-91515
raf = window.requestAnimationFrame
caf = window.cancelAnimationFrame
w = window
for vendor in ['ms', 'moz', 'webkit', 'o']
break if raf
raf = w["#{vendor}RequestAnimationFrame"]
caf = (
w["#{vendor}CancelAnimationFrame"] or
w["#{vendor}CancelRequestAnimationFrame"]
)
# rAF is built in but cAF is not.
if raf and not caf
browserRaf = raf
canceled = {}
raf = (fn) -> id = browserRaf (time) ->
return fn time unless id of canceled
delete canceled[id]
caf = (id) -> canceled[id] = true
# Handle legacy browsers which dont implement rAF
unless raf
targetTime = 0
raf = (fn) ->
targetTime = Math.max targetTime + 16, currentTime = +new Date
w.setTimeout (-> fn +new Date), targetTime - currentTime
caf = (id) -> clearTimeout id
export requestAnimationFrame = raf
export cancelAnimationFrame = caf
# setInterval, but for animations. :)
said = 1
handles = {}
export setAnimation = (fn) ->
id = said++
handles[id] = raf ifn = do (id) -> (time) ->
return unless handles[id]?
fn time
handles[id] = raf ifn
return id
export clearAnimation = (id) ->
caf handles[id]
delete handles[id]