Last active
December 22, 2015 05:48
-
-
Save Rich-Harris/6426380 to your computer and use it in GitHub Desktop.
A throttling function
This file contains 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 ( 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