Last active
August 4, 2016 04:27
-
-
Save romelperez/0d2660d89546c26003d54b48d90c9edb to your computer and use it in GitHub Desktop.
A throttle function for JavaScript.
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
/** | |
* 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