Skip to content

Instantly share code, notes, and snippets.

@romelperez
Last active August 4, 2016 04:27
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 romelperez/0d2660d89546c26003d54b48d90c9edb to your computer and use it in GitHub Desktop.
Save romelperez/0d2660d89546c26003d54b48d90c9edb to your computer and use it in GitHub Desktop.
A throttle function for JavaScript.
/**
* Returns a function that will be called once in an interval of time right
* away when it is called.
*
* @param {Function} func - The function to throttle.
* @param {Number} interval - Time in milliseconds.
* @param {Function} gate - The function to validate the throttle. If it return
* true, we prevent the throttle.
*
* @return {Function}
*/
const throttle = function (func, interval = 1000, gate = function () {}) {
'use strict';
if (typeof func !== 'function') {
throw new Error('Expected function as first parameter');
}
let available = true;
let queue = false;
return function () {
const args = arguments;
const call = () => {
available = false;
func.apply(this, args);
setTimeout(() => {
if (queue) {
queue = false;
call();
} else {
available = true;
}
}, interval);
};
if (gate() || available) {
call();
} else {
queue = true;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment