Skip to content

Instantly share code, notes, and snippets.

@JoeSz
Last active October 7, 2016 14:43
Show Gist options
  • Save JoeSz/2bc086557d839766f3fae79b7fcc2541 to your computer and use it in GitHub Desktop.
Save JoeSz/2bc086557d839766f3fae79b7fcc2541 to your computer and use it in GitHub Desktop.
Timed Interval
/**
* timedInterval
*
* The method calls a function or evaluates an expression at specified intervals (in milliseconds)
* until a specified number of milliseconds.
*
* @param {Function} callback
* @param {int} interval - run every [interval] ms
* @param {int} expiration - run until [expiration] in ms
* @param {mixed} callbackArgs - arguments for callback function
* @return {function}
*/
function timedInterval(callback, interval, expiration, callbackArgs = null) {
var wait = false;
return function() {
if ( wait ) {
return;
}
wait = true;
var handle = setInterval(function() {
callback.call( callbackArgs );
}, interval);
setTimeout(function() {
clearInterval( handle );
wait = false;
}, expiration);
};
};
// Example:
var onScroll = timedInterval(function(){
// code
}, 500, 10000, null);
$( window ).on( "scroll", onScroll );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment