Skip to content

Instantly share code, notes, and snippets.

@spoike
Last active August 13, 2017 21:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spoike/9e258febc6a94f3e5ed3 to your computer and use it in GitHub Desktop.
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/
(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
Copy link

csainty commented Aug 4, 2014

@spoike Missing a return on line 5?

@spoike
Copy link
Author

spoike commented Aug 4, 2014

@csainty Oops, fixed!

@voigtan
Copy link

voigtan commented Aug 5, 2014

line 5... should be 1000 / defaultFrameRate right?

@spoike
Copy link
Author

spoike commented Aug 5, 2014

Thanks @voigtan

@MeoMix
Copy link

MeoMix commented Apr 27, 2015

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.

@ptbrowne
Copy link

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