DEV Community

Cover image for The shortest explanation of debouncing & throttling in JavaScript
Kostya Proshin
Kostya Proshin

Posted on

The shortest explanation of debouncing & throttling in JavaScript

If you're searching for a gist of throttling and debouncing and you don't have much time to spare, you came to the right place! 🔥

You can use both these optimization tricks to reduce the number of function calls in response to events that fire frequently.

Let's jump directly to the example.

<p id="count">0</p>
<button id="btn" type="button">I'm a button, click me!</button>
Enter fullscreen mode Exit fullscreen mode
let count = 0
const btn = document.querySelector('#btn')

btn.addEventListener('click', handleClick, false)

function handleClick() {
  const counter = document.querySelector('#count')
  counter.innerHTML = ++count
}
Enter fullscreen mode Exit fullscreen mode

As you notice, we can increment the count by clicking the button.

We can go slow and push the button from time to time. Or we can go at light speed and hit the button as quickly as possible.

In both scenarios, code in the handler will run every time we click the button. So let's consider it as our baseline.

Imagine that we want to optimize this functionality.

Let's change our code to use debouncing.

let count = 0, timer = null
const btn = document.querySelector('#btn')

btn.addEventListener('click', handleClick, false)

function handleClick() {
  if (timer) {
    clearTimeout(timer)
  }

  timer = setTimeout(() => {
    const counter = document.querySelector('#count')
    counter.innerHTML = ++count
  }, 3000)
}
Enter fullscreen mode Exit fullscreen mode

Now, no matter how often we push the button, the handler will increment the count only three seconds after we stopped hitting the button.

So, debouncing is when you execute code only after a certain period some event stops firing.

This trick can help handle user input. E.g., we can send an HTTP request not on every keystroke but only when the user stops typing.

Now let's look at throttling.

let count = 0, timer = null
const btn = document.querySelector('#btn')

btn.addEventListener('click', handleClick, false)

function handleClick() {
  if (timer) return

  timer = setTimeout(() => {
    const counter = document.querySelector('#count')
    counter.innerHTML = ++count
    timer = null
  }, 3000)
}
Enter fullscreen mode Exit fullscreen mode

In that case, no matter how often we push the button, the handler will increment the count only one time in three seconds.

Thus, throttling is when you execute code at a regular interval during some event firing.

You can use it to optimize the handling of a scroll event.

There you have it! I hope I saved you some time googling.

Thank you for reading! 😜

Discussion (0)