/**
* Throttles DOM element requests to limit the rate of function calls.
*
* @param {Function} func The function to throttle.
* @param {number} delay The delay in milliseconds between requests.
* @param {HTMLElement} element The DOM element to associate the throttling with.
*/
function throttleDOM(func, delay, element) {
let timeoutId = null;
let lastExecTime = 0;
const throttledFunc = function(...args) {
const now = Date.now();
const timeSinceLastExec = now - lastExecTime;
if (!timeoutId) {
if (timeSinceLastExec >= delay) {
func.apply(this, args); // Execute if enough time has passed
lastExecTime = now;
} else {
timeoutId = setTimeout(() => {
func.apply(this, args); // Execute after delay
lastExecTime = Date.now();
timeoutId = null;
}, delay - timeSinceLastExec);
}
}
};
// Attach the throttled function to the element
element.addEventListener('click', throttledFunc);
}
export default throttleDOM;
Add your comment