Debounce in Js and its Importance

July 07, 2020

The debounce() forces a function to wait a certain amount of time before running again. it helps to prevent excess calls of Api's. debounce() function delay the processing of the keyup event until the user has stopped typing for a fixed amount of time and it helps to improve performance of project.

  • limit the amount of times a function call such as scroll-event, keyup-event, mousemove-event.
  • helps to prevent exceed calling of api's such as during a search movies in the search bar becoz it limit the call api or delay the call api
// create function expression debounce
const debounce =(func,delay)=>{
 let timeoutId;   // create undefined timeoutId variable
 return (...args)=>{
   timeoutId && clearTimeout(timeoutId) // cancels a timeout previously established by calling setTimeout().
   timeoutId = setTimeout(()=>{    
     func.apply(null,args)  //it takes arguments as an array
   },delay)
 }
}

Understand Debounce:

debounce is a higher order function, which is a function that return another function in this case it is anonymous function and it contains ...args as a spread operator

  • func: Excute after the debounce time.
  • delay: it is used to delay func. execution with setTimeOut
  • timeoutId : Variable timeoutId initial undefined variable
  • clearTimeout: The clearTimeout() method of the WindowOrWorkerGlobalScope mixin cancels a timeout previously established by calling setTimeout().
  • apply: Used to takes arguments as an array
// call debounce and passes a function and delay
searchBar.addEventListener('keyup',debounce((e)=> console.log(e),500))
  • Add addEventListener keyup in searchBar and call debounce return a function and delay of 500 ms
  • debounce helps to avoid excess calls of Api it calls 500 ms delay

Thanks 🙂🙂