1. /**
  2. * Throttles DOM element requests to limit the rate of function calls.
  3. *
  4. * @param {Function} func The function to throttle.
  5. * @param {number} delay The delay in milliseconds between requests.
  6. * @param {HTMLElement} element The DOM element to associate the throttling with.
  7. */
  8. function throttleDOM(func, delay, element) {
  9. let timeoutId = null;
  10. let lastExecTime = 0;
  11. const throttledFunc = function(...args) {
  12. const now = Date.now();
  13. const timeSinceLastExec = now - lastExecTime;
  14. if (!timeoutId) {
  15. if (timeSinceLastExec >= delay) {
  16. func.apply(this, args); // Execute if enough time has passed
  17. lastExecTime = now;
  18. } else {
  19. timeoutId = setTimeout(() => {
  20. func.apply(this, args); // Execute after delay
  21. lastExecTime = Date.now();
  22. timeoutId = null;
  23. }, delay - timeSinceLastExec);
  24. }
  25. }
  26. };
  27. // Attach the throttled function to the element
  28. element.addEventListener('click', throttledFunc);
  29. }
  30. export default throttleDOM;

Add your comment