Last active
November 10, 2017 01:09
-
-
Save Beraliv/3460b9938db15e3236976f372cdd2d7a to your computer and use it in GitHub Desktop.
Debounce and throttle lodash analogues
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
/** | |
* 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