Today I Learned - Rocky Kev

TIL about Debouncing/throttling

POSTED ON:

TAGS:

What is Debouncing, Throttling

(I'm yoinking from this comment here

Debouncing and throttling are too common techniques for dealing with things that happen "too often". Imagine you're meeting a friend, and they are telling you a story, but they struggle to pause when talking. Let's say you want to accommodate them while also responding to what they have to say, when possible. (I know this might be a bit contrived, but bear with me!)

The GOAL:
Let's say you can never speak at the same time.

Method 1: Synchronous
You could respond to each sentence the moment they finish it...

The issue: If your responses are short, it doesn't disrupt your friend's story. But if they're long, it can cause a lot of confusion.

Method 2: Debounced

You could wait for them to stop talking.

The issue:
It works if your friend is making pauses.
But if they aren't, then you can wait a long time before you get a chance.

If your friend makes pauses:

If your friend just keeps going:

Method 3: Throttled

You could decide to respond at most once a minute. Here, you keep count of how long you haven't spoken for. Once you haven't spoken for a minute, you insert your response right after the friend's next sentence:

This strategy is helpful if your friend wants you to respond as they go, but they don't ever create pauses for you to do it. But it's not great if they're creating pauses but you're still waiting out for no reason:

How this matters in the real world

Instead of your friend's sentences, think of events like clicking, or keyboard typing.

And your responses is updating the screen.

You use debouncing or throttling when the user is doing something too fast (e.g. typing), and updating the screen in response to each individual event is just too slow. So you either wait for the user to stop typing (debouncing) or you update the screen once in a while, like once a second (throttling).

Originally via React-18's ELI5 Discussion thread


Related TILs

Tagged:

TIL Indirection and Swallowing the error

Op shared a tryCatch util that is problematic.

TIL reusing variables

Do not reuse variables. Do not double define variables that represent the same thing.

TIL about semaphores

A semaphore limits access to a resource to some number of consumers. Any new requests for the resource will get stalled until later, eventually to be handled.