DEV Community

Cover image for How to use Lodash debounce method?
Leo Cuéllar for Devcore

Posted on • Originally published at devcore.io

How to use Lodash debounce method?

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:

const logHi = () => console.log('Hi')

const debouncedLogHi = _.debounce(logHi, 1500)

debouncedLogHi()
debouncedLogHi()
debouncedLogHi()

//console: Hi
Enter fullscreen mode Exit fullscreen mode

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:

const logMessage = message => console.log(message)

const debouncedLogMessage = _.debounce(logMessage, 1500)

debouncedLogMessage('first message')
debouncedLogMessage('second message')
debouncedLogMessage('third message')

//console: third message
Enter fullscreen mode Exit fullscreen mode

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.


This article was first published on devcore.io. go check it out!

Top comments (0)