Last active
August 13, 2017 21:35
-
-
Save spoike/9e258febc6a94f3e5ed3 to your computer and use it in GitHub Desktop.
Throttling using windows.requestAnimationFrame with fallback to lodash throttle. See more here: http://spoike.ghost.io/user-input-framerate-throttling-in-the-browser/
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
(function() { | |
var defaultFrameRate = 20, // fps lock for old browsers | |
// This is the default fallback throttle function | |
framerateThrottle = function(callback) { | |
return _.throttle(callback, 1 / (defaultFrameRate * 1000)); | |
}; | |
// Feature detection - should have requestAnimationFrame | |
if (window.requestAnimationFrame) { | |
framerateThrottle = function(callback) { | |
var mayUpdate = false, | |
update = function() { | |
mayUpdate = true; | |
window.requestAnimationFrame(update); | |
}; | |
// initial update | |
window.requestAnimationFrame(update); | |
// the function called by, e.g. an input event | |
return function() { | |
var thisArg = this; | |
// discard the invocation when mayUpdate | |
// is false (i.e. is throttled) | |
if (mayUpdate) { | |
mayUpdate = false; | |
return callback.apply(thisArg, arguments); | |
} | |
}; | |
}; | |
} | |
// Mix in the framerate throttle to lodash | |
_.mixin({ | |
framerateThrottle: framerateThrottle | |
}); | |
}()); |
@csainty Oops, fixed!
line 5... should be 1000 / defaultFrameRate right?
Thanks @voigtan
Hi... I have some serious concerns about this code.
How does the 'update' function ever terminate? It's self-recursive and all it does is set 'mayUpdate' to true.
Infinitely calling RAF N times where N is the number of functions throttled is really, really scary. I'm surprised nobody has brought this up.
I had the same concerns as MeoMix. I handed up rolling my own. I did not put feature detection. Here is the gist : https://gist.github.com/ptbrowne/cfe8318854b72ec1c9e62935a76ce54f, JSBin with tests : http://jsbin.com/jicajamohu/edit?html,js,output
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@spoike Missing a return on line 5?