Throttle & Debounce behavior (lodash)

Elena Sharovar
3 min readAug 23, 2017

Note: these results are received with lodash 4.17.4.

Definitions

Throttle — invokes function at most once per every X milliseconds.

Debounce — delays invoking function until after X milliseconds have elapsed since the last time the debounced function was invoked

Example

Imagine you have a function processLetter, which accepts a letter and somehow makes a processing (makes a call to some API). And you have some code which is calling your function 6 times in 45 milliseconds. This is a timeline of calls:

And you want to apply “throttle” so that processLetter is called not more often than once in 10 msec. You create a function processLetterThrottled = _.throttle(processLetter,10) and forward all calls to it.

Which values and when processLetterThrottled will pass to original function processLetter?

Answer:

Default throttle — which has settings {leading: true, trailing: true} — will result in these values being passed to processLetter:

What’s interesting here: “C” was omitted, but “E” was postponed till the end of 10-msec interval.

Leading Throttle — with settings {leading: true, trailing: false} — will result in these values being processed by processLetter:

Now, “B” and “D” are omitted. Algorithm omitted “D” because throttle interval is 10 msec, and exactly 10 msec ago “C” was processed.

Trailing throttle — {leading: false, trailing: true} will result in these values being processed:

Notice that F was processed later than it was emitted (on 55th milisecond). This is because algorithm was waiting for the end of 10-msec interval.

Debounce

Default debounce — which has settings {leading: false, trailing: true} — will pass to processLetter these values only:

Debounce with options set to {leading: true, trailing: true} will pass to processLetter these values:

Debounce with {leading: true} is passing first received value to debounced function. And then it works in same way as default debounce.

Debounce with {leading: true, trailing: false} will result in these values being processed.

So, as you see, using different settings you can get different results.

I hope this visual explanation helps a lot.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Access the best member-only stories.

Support independent authors.

Listen to audio narrations.

Read offline.

Join the Partner Program and earn for your writing.

Elena Sharovar

JavaScript Tech Lead, Waverley Software