Skip to content

Instantly share code, notes, and snippets.

@lifedraft
Last active December 29, 2015 10:09
Show Gist options
  • Save lifedraft/7655319 to your computer and use it in GitHub Desktop.
Save lifedraft/7655319 to your computer and use it in GitHub Desktop.
Debouncing Window Scroll events with requestAnimationFrame #jquery. Source: http://www.html5rocks.com/en/tutorials/speed/animations/
jQuery.request_scroll = (callback) ->
###
Callback for our scroll event - just
keeps a track on the last scroll value
###
onScroll = ->
lastScrollY = window.scrollY
requestTick()
###
Calls rAF if it's not already
been done already
###
requestTick = ->
unless ticking
requestAnimFrame update
ticking = true
###
Our animation callback
###
update = ->
callback lastScrollY
# allow further rAFs to be called
ticking = false
lastScrollY = 0
ticking = false
# only listen for scroll events
window.addEventListener "scroll", onScroll, false
# shim layer with setTimeout fallback
requestAnimFrame = (->
window.requestAnimationFrame or
window.webkitRequestAnimationFrame or
window.mozRequestAnimationFrame or
window.oRequestAnimationFrame or
window.msRequestAnimationFrame or
(timeout_callback) ->
window.setTimeout timeout_callback, 1000 / 60
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment