DEV Community

Cover image for Debouncing in Javascript using a custom function or Lodash library.
Samuel Egbajie
Samuel Egbajie

Posted on • Edited on

Debouncing in Javascript using a custom function or Lodash library.

What A Debounce function is

Wait, you are a Javascript developer trying to implement a function to only fire after an interval from when a certain action or event is triggered and you have tried and still not gotten it the right way.

Worry no more as I would put together two ways of doing this the right way without you getting to crack your head so hard and that is what a debounce function solves.

1.) Debouncing using a custom JS function

const debounceTime = (fn, T)=>
{
let timer;
  return function() {
    if(timer) clearTimeout(timer)
    timer=setTimeout(fn, T)
  }
}
Enter fullscreen mode Exit fullscreen mode

This function takes in two parameters, a function, fn() to be debounced and the time interval, T to wait for the action to run.

Example, we want a callback function that would be called after 1000 Milliseconds or 1 seconds, we would just call the debounceTime function with parameters of the callback function and 1000 Milliseconds.
The function would log "I debounced after 1 seconds" just after 1 second in the console.

debounceTime(()=>{
console.log("I debounced after 1 seconds")
}, 1000)
Enter fullscreen mode Exit fullscreen mode

2.) Debouncing using a Lodash
For you to be able use the lodash package on your Node.js Environment,
you have to first install the lodash package using $ npm i --save lodash for npm or $ yarn add lodash for yarn through your command line interface,
after that, you import it into your the file you want to apply it.
import {debounce} from "lodash"

debounce(()=>{
console.log("I debounced after 1 seconds")
}, 1000)
Enter fullscreen mode Exit fullscreen mode

The above use case would work exactly as the example using the custom JS function

I hope it helped 😀 😀 😀
Thanks for reading and Happy coding!!!

Top comments (0)