Files
30-seconds-of-code/test/throttle/throttle.js
Angelos Chalaris 06d7e04220 Added some tests
2018-01-28 16:28:54 +02:00

21 lines
433 B
JavaScript

const throttle = (fn, wait) => {
let inThrottle, lastFn, lastTime;
return function() {
const context = this,
args = arguments;
if (!inThrottle) {
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
clearTimeout(lastFn);
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
}, wait - (Date.now() - lastTime));
}
};
};
module.exports = throttle