Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Last active December 22, 2015 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/6426380 to your computer and use it in GitHub Desktop.
Save Rich-Harris/6426380 to your computer and use it in GitHub Desktop.
A throttling function
(function ( global ) {
'use strict';
var throttle;
if ( typeof Date.now !== 'function' ) {
Date.now = function () {
return new Date().getTime();
};
}
throttle = function ( fn, options ) {
var active, timeout, nextAllowed, scheduled;
if ( typeof options !== 'object' ) {
options = {
delay: options
};
}
if ( !options.delay ) {
options.delay = 250; // default value is 250 milliseconds
}
return function () {
var args, timeNow, call, context;
args = arguments;
timeNow = Date.now();
context = options.context || this;
call = function () {
fn.apply( context, args );
nextAllowed = Date.now() + options.delay;
scheduled = false;
};
// if it's been less than [delay] since the last call...
if ( timeNow < nextAllowed ) {
// schedule a call, if one isn't already scheduled
if ( !scheduled ) {
setTimeout( call, nextAllowed - timeNow );
scheduled = true;
}
}
else {
call();
}
};
};
// export as CommonJS module...
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = throttle;
}
// ... or as AMD module...
else if ( typeof define !== 'undefined' && define.amd ) {
define( function () { return throttle; });
}
// ... or as browser global
else {
global.throttle = throttle;
}
}( typeof window !== undefined ? window : this ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment