How to use Lodash debounce method?

Published July 5, 2021, Modified July 5, 2021

Recently I was applying for a react developer position at some company. In the process, I had to solve three tasks, which, surprisingly, were not so hard as people implied in some reviews I read.

For a React dev position, in almost every interview you may take for any company, you will be asked to fetch data from an API and use it somehow, which was no exception on this occasion.

The catch for me was that I was required to use the debounce() method from the lodash library, and to be honest, I’ve heard of the library, but I’ve never used it before.

Let me tell you what I learned from this interview.

What is lodash?

So, basically, lodash is a utility library that simplifies common programming tasks and gives us more capabilities when executing them.

I would love to give you a lot of examples but let me save that for future articles.

What is a debounced function?

A debounced function is a function that delays its execution a certain amount of milliseconds after the last call was received.

Let’s separate the three types of functions involved in this:

  1. Your normal function: this is the function that you want to debounce
  2. The debounced function: your same function but debounced, which means that it will work as the definition above says.
  3. The debounce function: a function that will receive two parameters, a function to debounce and some time in milliseconds. This function will return the debounced function.

Lodash debounce() method is that debounce function mentioned in point 3.

Let’s see it with a simple example:

1const logHi = () => console.log('Hi')
3const debouncedLogHi = _.debounce(logHi, 1500)
9//console: Hi

In this case, the timer will start running from the last call of the debouncedLogHi() function. After 1500 milliseconds, the function will run.

Passing parameters to a debounced function

You can also pass parameters to a debounced function:

1const logMessage = message => console.log(message)
3const debouncedLogMessage = _.debounce(logMessage, 1500)
5debouncedLogMessage('first message')
6debouncedLogMessage('second message')
7debouncedLogMessage('third message')
9//console: third message

As you can see, once the timer ends after the last call to the debounced function, the invoked function will be the last.

Wrapping Up

So yeah, lodash is awesome, and I'll definitely write more about it in the future. Subscribe to my newsletter if you want to be posted about future posts.

author image

Hi, I'm Leo Cuéllar. I'm a Software Engineer, technical interviewer, and technical writer. I'm also the founder of Devcore. I enjoy writing about front-end and job interview topics.

🌌 Join the Devcore

Subscribe and receive a weekly email with the most popular articles about modern front-end web development, the latest interview questions and the most relevant job opportunities.

No spam. Unsubscribe anytime.