# Debounce and Throttle

## Purpose

* Used to prevent from the event has triggered for many times due to user behavior
* E.g: user press the same button for several times in a second to fetch the data which may affect the performance

## Debounce

* The event will be triggered when the event is not be called in the specific time interval

```javascript
 const debounce = (callFn, time) => {
    let timer = null;
    return () => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        callFn();
      }, time);
    };
  };
  
  const test = debounce(() => {
    console.log("test");
  }, 1000);
```

## Throttle

* The numbers of event triggered is limited not more than once in every time interval

```javascript
// Version 1
const throttle = (callbackFn, time) => {
    let valid = true;
    return () => {
      if (valid) {
        callbackFn();
        valid = false;
        setTimeout(() => {
          valid = true;
        }, time);
      }
    };
};

// Version 2
// including trigger last event automatically after time is over
const throttle = (func, limit) => {
  let lastFunc;
  let lastRan;
  return () => {
    const context = this
    const args = arguments
    if (!lastRan) {
      func.apply(context, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(function() {
        if ((Date.now() - lastRan) >= limit) {
          func();
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}

const test = throttle(() => {
    console.log("test");
}, 2000);
```

## Difference

1. Debounce is to execute the latest function of the repeated function call in the time interval
2. Throttle is to execute the earliest function of repeated function in time interval

{% embed url="https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf" %}

{% embed url="https://css-tricks.com/debouncing-throttling-explained-examples/" %}
