Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active November 10, 2017 01:09
Show Gist options
  • Save Beraliv/3460b9938db15e3236976f372cdd2d7a to your computer and use it in GitHub Desktop.
Save Beraliv/3460b9938db15e3236976f372cdd2d7a to your computer and use it in GitHub Desktop.
Debounce and throttle lodash analogues
/**
* For clafirying go to https://css-tricks.com/the-difference-between-throttling-and-debouncing/
*
*/
count DEFAULT_DEBOUNCE_TIME = 400;
const DEFAULT_THROTTLE_TIME = 400;
let debounce = (fn, time = DEFAULT_DEBOUNCE_TIME) => {
let timeoutId;
return (...args) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
return Promise((resolve, reject) => {
timeoutId = setTimeout(() => {
Promise.resolve(fn(...args))
.then((...promiseArgs) => resolve(...promiseArgs))
.catch((...promiseArgs) => reject(...promiseArgs));
}, time);
});
};
};
let throttle = (fn, time = DEFAULT_THROTTLE_TIME) => {
let running = false;
return (...args) => {
if (running) {
return Promise.reject();
}
running = true;
setTimeout(() => {
running = false;
}, time);
return Promise.resolve(fn(...args));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment