JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<p>
Explanation:

The debounce function takes a function (func) and a delay time (delay) as parameters. It returns a new function that wraps the original function with debouncing logic.

Inside the returned function, a timer (timer) is used to track the delay period.

When the debounced function is called, the clearTimeout function is used to clear any existing timer.

A new timer is set using setTimeout, and it delays the execution of the original function (func) by the specified delay time.

The apply method is used to call the original function with the correct context (this) and arguments (args).

The debouncedHandleScroll function is created by passing your original handleScroll function and the desired delay (200ms) to the debounce function.

Finally, the debouncedHandleScroll function is attached to the scroll event.
</p>

Dry Run:

Let's consider a scenario where the user starts scrolling and then stops after 150ms:

The handleScroll function is called when the user starts scrolling.
The clearTimeout clears any existing timers.
A new timer is set to execute the handleScroll function after 200ms.
The user stops scrolling after 150ms, and the timer is not yet triggered.
The handleScroll function is not executed immediately but will be executed after the remaining 50ms of the delay.
Complexity:

The time complexity of this debouncing implementation is O(1) because the debounced function executes with a constant delay, regardless of the number of times it is called. The space complexity is also O(1) as it uses a constant amount of space for the timer variable.

JavaScript

// Functional Programming Debounce Function
const debounce = (func, delay) => {
  let timer;
  
  return function (...args) {
    clearTimeout(timer);
    
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
};

// Your handleScroll function
const handleScroll = () => {
  // Your scroll handling logic goes here
  console.log('Handling scroll...');
};

// Debounce the handleScroll function
const debouncedHandleScroll = debounce(handleScroll, 200);

// Attach the debounced function to the scroll event
window.addEventListener('scroll', debouncedHandleScroll);