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.
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.
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:
- Your normal function: this is the function that you want to debounce
- The debounced function: your same function but debounced, which means that it will work as the definition above says.
- 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.
debounce() method is that debounce function mentioned in point 3.
Let’s see it with a simple example:
1const logHi = () => console.log('Hi')23const debouncedLogHi = _.debounce(logHi, 1500)45debouncedLogHi()6debouncedLogHi()7debouncedLogHi()89//console: Hi10
In this case, the timer will start running from the last call of the debouncedLogHi() function. After 1500 milliseconds, the function will run.
You can also pass parameters to a debounced function:
1const logMessage = message => console.log(message)23const debouncedLogMessage = _.debounce(logMessage, 1500)45debouncedLogMessage('first message')6debouncedLogMessage('second message')7debouncedLogMessage('third message')89//console: third message10
As you can see, once the timer ends after the last call to the debounced function, the invoked function will be the last.
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.
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.