Topic Description

Throttling refers to executing a callback function only once within a specified time period (t) when an event is triggered. If new events are triggered during this time, the callback function is not executed.

Please implement a throttle function throttle that takes two parameters: the first parameter is a callback function fn, and the second parameter is the delay time delay. This function follows the behavior described above.

Answer


function **throttle**(fn, delay=500) {
  let timer = null
  
  return function(...args){
	  if(timer) return
	  
	  timer = setTimeout(()=>{
		  timer = null
	  }, delay)
	  
	  fn.apply(this, args)
  }
}
function throttle(fn, delay = 500) {
  let timer = null;

  return (...args) => {
    if (timer) return;
    timer = setTimeout(() => {
      fn(...args);
      timer = null;
    }, delay);
  };
}