Debouncing: The “Wait, Let Me Finish”
Imagine you’re at a coffee shop, and you’re trying to order. You start telling the barista(a person who prepares and serves coffee drinks) your order, but they interrupt you mid-sentence to ask a question. You’d probably say, ” Wait, let me finish.” Debouncing works similarly. It’s a technique that ensures a function is only executed after a certain delay, even if the event that triggers it fires multiple times.
When to use Debouncing?
- Search bars: When users type in a search bar, you should wait until they’ve finished typing before sending a request to the server.
- API calls: If you’re making API calls based on user input, debouncing can help reduce the number of requests and prevent the server from overheating.
How do you use Debounce?
Here’s an example of debouncing in a real-world scenario:
Debouncing a Virtual Wardrobe
Imagine you’re building a virtual wardrobe app where users can filter clothes based on various criteria like color, size and style. You want to fetch new clothes from the database as the user types in the filter criteria. However, you don’t want to fetch clothes on every keystroke, as this would lead to unnecessary database queries.
Code example:
function debounce(func, delay) //defines a function named debounce that takes two arguments:func(the function to debounce) and delay(the delay time in milliseconds) { let timeoutid;//declares a variable timeout to store the ID of the timeout return function(...args)// returns a new function that takes any number of arguments. { clearTimeout(timeoutId);//clears the previous timeout if it exists. timeoutId = set Timeout(()=> func.apply(this, args), delay);// Sets a new timeout to execute the func function after the specified delay }; } //Example: Debouncing a virtual wardrobe filter const filterClothes = debounce((filterCriteria) => { console.log(`Fethching clothes with filter criteria: ${filterCriteria}`); //Fetch clothes from the database based on filter criteria },500); document.getElementById("filter-input").addEventListener("input",(event)=>{ const filterCriteria = event.target.value; filterClothes(filterCriteria);});
How it Works
- The user types in the filter input box.
- The filterClothes function is debounced with a delay of 500ms.
- If the user types again within the 500ms delay, the previous timeout is cleared, and a new timeout is set.
- Once the user stops typing for 500ms, the filterClothes function is executed, fetching clothes from the database based on the filter criteria.
Throttling: The “One at a time, Please”
Now, imagine a popular coffee shop with a long line. To manage the flow of customers, the staff might ask people to enter one at a time. Throttling works in similar way . It’s a technique that ensures a function is executed at a fixed rate , even if the event that triggers it fires more frequently .
When to use Throttling?
- Scrolling and resizing: When handling scroll or resize events, throttling can help prevent excessive function calls and improve performance.
- Mouse Movements: if you’re tracking mouse movements, throttling can help reduce the number of function calls and prevent performance issues.
How do you use throttling?
Here’s an example of debouncing in a real-world scenario:
Throttling a Live Sports Scoreboard
Imagine you’re building a live sports scoreboard that updates in real-time. You want to fetch new scores from the API whenever the user interacts with the scoreboard. However, you don’t want to fetch scores too frequently, as this would lead to unnecessary API calls.
Code example:
function throttle(func, interval)//Defines a function named throttle that takes two arguments: func (the function to throttle) and interval (the minimum time interval between executions). { let lastTime = 0; return function (...args) { const now = Date.now();//Gets the current timestamp in milliseconds. if (now - lastTime >= interval)//Checks if the time elapsed since the last execution is greater than or equal to the specified interval. { lastTime = now;//Updates the lastTime variable to the current timestamp if the interval condition is met. func.apply(this, args);//Executes the original function with the current context (this) and arguments (args) if the interval condition is met. } }; } // Example: Throttling a live sports scoreboard update const updateScoreboard = throttle((teamName) => { console.log(`Updating scoreboard for ${teamName}...`); // Fetch new scores from API for the specified team }, 1000); document.getElementById("team-selector").addEventListener("change", (event) => { const teamName = event.target.value; updateScoreboard(teamName); });
How it Works
- The user selects a team from the dropdown menu.
- The updateScoreboard function is throttled with an interval of 1second.
- If the user selects another team within the 1second interval, the updateScoreboard function is not executed.
- Once the 1second interval has passed since the last team selection, the updateScoreboard function is executed, fetching new scores from the API for the selected team.
By throttling the updateScoreboard function, you can reduce the number of unnecessary API calls and improve the performance of your live sports scoreboard.