spoike
8/4/2014 - 7:41 AM

Throttling using windows.requestAnimationFrame with fallback to lodash throttle. See more here: http://spoike.ghost.io/user-input-framerate-

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
    });
}());