Debounce

/** * Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. * @see {@link https://davidwalsh.name/javascript-debounce-function} * @param {Function} func Callback function * @param {Number} wait Wait for miliseconds until next execution * @param {Boolean} immediate Do not wait * @returns {Function} func * @example * const myEfficientFn = debounce(() => { console.log("hello") }, 250); window.addEventListener('resize', myEfficientFn); */ export default function debounce(func, wait, immediate) { let timeout; return () => { const context = this; // eslint-disable-next-line prefer-rest-params const args = arguments; const later = () => { timeout = null; if (!immediate) func.apply(context, args); }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.