Efficient function with throttle and debounce

/** * Very efficient function with debounce and throttle events * @param {HTMLElement} target Target element for eventListener * @param {EventListener} eventListener EventListener * @param {func} func Callback function * @param {Number} time Wait for miliseconds after each call * @param {Boolean} callOnLoad Call func when this function is called * @returns {void} * @example * myEfficientFn(window, 'scroll', () => { return console.log('hello'); }, 100, true); */ function myEfficientFn(target, eventListener, func, time, callOnLoad) { /** * Throttle function * @see {@link https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf} * @param {Function} f Callback function * @param {Number} w Wait for miliseconds until next execution * @returns {Function} Calls callback function * @example * window.addEventListener('scroll', throttle(() => { return console.log('hello') }, 100)); */ function throttle(f, w) { /** @type {Boolean} Is throtteling */ let t; return function () { /** @type {*} Arguments */ const a = arguments; /** @type {*} Context */ const c = this; if (!t) { f.apply(c, a); t = true; setTimeout(() => (t = false), w); } }; } /** * 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} f Callback function * @param {Number} w Wait for miliseconds until next execution * @param {Boolean} i Do not wait * @returns {Function} func * @example * window.addEventListener('scroll', debounce(() => { console.log('hello'); }, 100)); */ function debounce(f, w, i) { /** @type {Number|null} Timeout */ let t; return () => { /** @type {*} Arguments */ const a = arguments; /** @type {*} Context */ const c = this; const later = () => { t = null; if (!i) f.apply(c, a); }; /** @type {Boolean} Call now */ const n = i && !t; clearTimeout(t); t = setTimeout(later, w); if (n) f.apply(c, a); }; } // Call on load if (callOnLoad) { func.call(); } // Throttle target.addEventListener( eventListener, throttle(() => { return func.call(); }, time) ); // Debounce target.addEventListener( eventListener, debounce(() => { func.call(); }, time) ); }

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.