Topic Description

Create a function that takes another function fn and a time interval t in milliseconds as parameters. It should return a debounced version of the fn function. Debouncing refers to delaying the execution of a function by t milliseconds. If the function is called again within this delay period, the original execution is canceled.

Example:

Consider t = 50 milliseconds. If the function is called at 30ms, 60ms, and 100ms, the first two calls will be canceled, and the third call will execute at 150ms. If t is changed to 35 milliseconds, the first call will be canceled, the second call will execute at 95ms, and the third call will execute at 135ms.

Answer


function debounce(fn, t) {
  let timer
  
  return function(...args){
	  clearTimeout(timer)
	  
	  timer = setTimeout(()=>{
		  fn(...args)
	  }, t)
  }
}