Created
June 23, 2015 07:09
-
-
Save milesleif/498715f2b2410c56867a to your computer and use it in GitHub Desktop.
Queueable loop for RequestAnimationFrame
This file contains hidden or 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
| var ReqAF = function($){ | |
| var reqAnimationFrame = function(){ | |
| // Detect request animation frame | |
| var reqAnimationFrame = window.requestAnimationFrame || | |
| window.webkitRequestAnimationFrame || | |
| window.mozRequestAnimationFrame || | |
| window.msRequestAnimationFrame || | |
| window.oRequestAnimationFrame || | |
| // IE Fallback, you can even fallback to onscroll | |
| function(callback){ window.setTimeout(callback, 1000/60) ; }; | |
| return reqAnimationFrame; | |
| }(); | |
| var AFLoopCallbacks = []; | |
| var addToAFLoop = function(fn){ | |
| AFLoopCallbacks.push(fn); | |
| }; | |
| var startAFLoop = function(){ | |
| var lastPosition = -1; | |
| var loop = function(){ | |
| if (lastPosition === window.pageYOffset) { | |
| reqAnimationFrame(loop); | |
| return false; | |
| } | |
| $.each(AFLoopCallbacks, function(index, fn){ | |
| fn(); | |
| }); | |
| lastPosition = window.pageYOffset; | |
| reqAnimationFrame( loop ); | |
| }; | |
| if(AFLoopCallbacks.length > 0){ | |
| loop(); | |
| } | |
| }; | |
| // api | |
| return{ | |
| AFLoopCallbacks : AFLoopCallbacks, | |
| startAFLoop : startAFLoop, | |
| addToAFLoop : addToAFLoop | |
| }; | |
| }(jQuery); | |
| // usage | |
| // add any function to the loop | |
| // ReqAF.addToAFLoop(fn); | |
| // start the loop | |
| // ReqAF.startAFLoop(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment