Tip#15 Delay execution with _.debounce

User is typing example

David is typing…

Debounce is a technique to delay expensive executions, like a remote request or long calculations. In browser land, we're talking about few hundreds of milliseconds.

The official docs shows a ajax sample using Lodash debounce implementation, that's the most common one. But I'd like to show you a different one.

You are chatting with your friend David over WhatsApp, Slack, whatever, and while you wait his answer, a message appears saying "David is typing". After 3 seconds, the message disappears and suddenly appears again.

The logic to implement that is simple. When the user start typing, set a variable typing to true, and create a timeout of 3 seconds that set's the variable typing back to false, then use that variable to show/hide the message.

But the problem is that while the user is typing, you have to cancel the last timeout, and create a new one, after every single keystroke. That's what debounce is for, check it out how easy is the code:

We set a watch to the message property that resets typing to false after 3 seconds. The debounce take care of the rest.

Remember to never use the fat arrow function like this:

message: _.debounce(() => this.typing = false, 3000)

That's prettier and tempting, but wouldn't work, cause the scope is different.

What're you using _.debounce for? Let me know in the comments below.