| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { useCallback, useRef } from '@wordpress/element'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Get debounced version of a function that only runs a given amount of time |
| 8 |
* after the last time it was run. |
| 9 |
* |
| 10 |
* @param {Function} callback Function to debounce. |
| 11 |
* @param {number} delay Milliseconds to delay. |
| 12 |
* @returns {Function} Debounced function. |
| 13 |
*/ |
| 14 |
export const useDebounce = (callback, delay) => { |
| 15 |
const timeout = useRef(null); |
| 16 |
|
| 17 |
return useCallback( |
| 18 |
(...args) => { |
| 19 |
window.clearTimeout(timeout.current); |
| 20 |
|
| 21 |
timeout.current = window.setTimeout(() => { |
| 22 |
callback(...args); |
| 23 |
}, delay); |
| 24 |
}, |
| 25 |
[callback, delay], |
| 26 |
); |
| 27 |
}; |
| 28 |
|