Home > Web Front-end > JS Tutorial > Never Forget Debounce and Throttle Again. Visualise them - Codepen included

Never Forget Debounce and Throttle Again. Visualise them - Codepen included

DDD
Release: 2024-10-26 09:56:30
Original
218 people have browsed it

This is not just another article trying to explain how Debounce or Throttling works at code level rather this is an illustration to remember and visualise the concept so that you can practically apply them at your work.

Personally, I often find myself forgetting the concepts of debouncing and throttling, so when someone asks me to explain them—or if a question pops up in an interview—I just blink ?. To avoid that, I made a simple page to help refresh my memory. If you don't want to feel like an imposter follow along ?.

In the below codepen I have set the delay to 2 seconds for both debounce and throttle. Try clicking on random food items and give a pause.

Index

  • The Restaurant Analogy
  • Explanation
    • Why Debounce or Throttle anyway ?
    • JS Event Handler
    • Whats wrong ?
    • Debounce
    • Throttle

Never Forget Debounce and Throttle Again. Visualise them - Codepen included

Link to page

ashiqsultan.github.io

GitHub Link

Restaurant Analogy

Imagine you're at a restaurant and want to order some food, so you pick the menu from the table and you just start to read all the items. (In the webpage I shared, clicking different food items will be equivalent to reading the menu item)

The analogy here

  • ? Reading food item = ? Button Click
  • ?‍? Waiter going to kitchen = ? API call

And imagine there are three different types of waiters at the restaurant who could serve you:

  1. ?‍♂️ Normal Waiter

    • Takes note every single time you mention an item
    • Runs to the kitchen for each individual item
    • Like JS handling every single event immediately
  2. ? Debounced Waiter

    • When you start reading the menu he will be waiting for you to pause for atleast 2 seconds before taking the order.
    • Like waiting for a user to finish typing before making an API call
  3. ?‍? Throttled Waiter

    • Takes orders only once every 2 seconds
    • If you mention multiple items within those 2 seconds, they'll all go in the same order
    • Like limiting API calls to once every X seconds, regardless of user activity

Note: The main difference is:

  • Debouncing: Waits for activity (button click) to STOP for a specified time to trigger
  • Throttling: Triggers at REGULAR intervals, regardless of when an activity is stopped
  • Also 2 sec is just something I used as example it can be any timeperiod

Explanation

Why Debounce or Throttle anyway?

Before understanding debounce or throttle we need to know why are they even used in the first place. To know that lets understand behaviour of JS event handlers

Event Handlers in JS

In JS, event handlers are just functions that execute when specific events (like clicks, typing, or scrolling) occur. By default, these handlers will fire every single time the event happens - every keystroke, every click, or scroll movement.

// Basic event handler
button.addEventListener('click', function() {
    console.log('Button clicked!');
});

// Basic keystroke handler
input.addEventListener('keyup', function() {
    console.log('Key pressed!');
});
Copy after login

Whats wrong?

Say for example you have a button that would make an API call

function makeApiCall() {
  console.log("API call made");
}

button.addEventListener('click', () => {
  makeApiCall();
});
Copy after login

The above function will execute the makeApiCall() on each button click (i.e) if you manage to press it 10 times within 1 sec, guess what you have made 10 api calls in 1 sec. This is the default behaviour.

But firing an API call every single time for an event can be inefficient and most times this is not what you are looking for. This is where throttling and debouncing come in to picture.

If you want to take away a definition from this article may be this is the one. Throttling and debouncing are two most common ways to control an Event Listener’s response rate.

Debouncing

I’m not going to explain the code for debouncing as this can just be imported from lodash, rather we will see where you can actually use it.

Use Debouncing when you want to make the api call only if the user has stopped typing for a certain amount of time or stopped clicking for a certain amount of time.

In our example if the user keeps clicking on the button even for 5 min straight, the api call will be made only once.

So two things are happening here:

  • User needs to stop clicking.
  • Stop clicking means atleast for 2 seconds there should be no clicking on the button.

Throttle

Throttle is like an interval. Use this when you dont want to wait till the user stops rather make an api call on every interval say 2 seconds

Example if the user is typing for 1 minute straight without pausing then for every 2 sec you would be calling the API.

Conclusion

As mentioned in the article this is not to explain how the functions work rather to visualise and understand why its used. I would surely recommend you to understand at code level how they work but personally would still use the debounce and throttle provided by lodash library and not to reinvent the wheel.

If you like the article leave a thumbs up, it would really motivate me to write more. Thanks ?.

The above is the detailed content of Never Forget Debounce and Throttle Again. Visualise them - Codepen included. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template