|
| 1 | +export default debounce |
| 2 | + |
| 3 | +/** |
| 4 | + * Original Source: https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript |
| 5 | + * This method will prevent functions to be called repeatedly |
| 6 | + * @param {Function} func Function to debounce |
| 7 | + * @param {Number} [delay=0] The number of milliseconds to delay the function call |
| 8 | + * @param {Boolean} [immediate=false] |
| 9 | + * Weather to call the function and then wait or vice versa |
| 10 | + * @returns {Function} Returns the new debounced function. |
| 11 | + * @example |
| 12 | + * // Log the event after 1000ms of the last call |
| 13 | + * const debounced = debounce(console.log, 1000) |
| 14 | + * window.addEventListener('keyup', debounced) |
| 15 | + * |
| 16 | + * // Log the event immediately and wait 1000ms for the next call |
| 17 | + * const debounced = debounce(console.log, 1000, true) |
| 18 | + * window.addEventListener('keyup', debounced) |
| 19 | + * |
| 20 | + * // If 'delay' is falsy (except for 0), the function will not be debounced |
| 21 | + * const debounced = debounce(console.log) |
| 22 | + * window.addEventListener('keyup', debounced) |
| 23 | + */ |
| 24 | +function debounce(func, delay, immediate) { |
| 25 | + let timeout |
| 26 | + if (typeof func !== 'function') { |
| 27 | + throw new TypeError('Expected a function') |
| 28 | + } |
| 29 | + return (...args) => { |
| 30 | + const callNow = immediate && !timeout |
| 31 | + if (!delay && delay !== 0) { |
| 32 | + func(...args) |
| 33 | + } else { |
| 34 | + clearTimeout(timeout) |
| 35 | + |
| 36 | + timeout = setTimeout(() => { |
| 37 | + timeout = null |
| 38 | + if (!immediate) { |
| 39 | + func(...args) |
| 40 | + } |
| 41 | + }, delay) |
| 42 | + |
| 43 | + if (callNow) { |
| 44 | + func(...args) |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments