/**
* throttle
*
* @since 1.3.0
* @author caiyue;
* @param func {function}
* @param wait {number}
*
* @example
*
* var debounced = throttle(()=>{console.log(123)}, 500);
* //cancel the throttle function
* debounced.cancel();
*/
const throttle = (func, wait) => {
if (typeof func !== 'function') {
throw new TypeError('Expected a function');
}
let timerId;
let startTime = 0;
function cancel() {
clearTimeout(timerId);
//reset countdown
startTime = 0;
}
function debounced() {
let now = Date.now();
// start countdown
if (!startTime) {
startTime = now;
}
// countdown over
if (now - startTime >= wait) {
func();
// reset countdown
startTime = 0;
return;
}
clearTimeout(timerId);
timerId = setTimeout(() => {
func();
// reset countdown
startTime = 0;
}, wait);
}
debounced.cancel = cancel;
return debounced;
};
export default throttle;
Source