Throttling in JS
Tags: throttling, javascript, webdev, learndev
Published: 2024-06-23 19:16:10

## Throttling

- 
**Throttling** in JavaScript is a technique used to control the rate at which a function is executed. 

- This is especially useful in scenarios where a function could be called frequently, such as during **scroll events**, **window resizing**, or **handling user input** in real-time. 

- By throttling a function, you ensure that it is not executed more often than a specified interval, thereby improving performance and responsiveness of the application.


![boy-throttles-bike](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mg8602p4m7il15bijo7a.gif)

Ok ok we will not go into too much of theories and stuff but just remember that throttling means **preventing a functional call which might called continuously**.



### Here's how throttling works...
- So we have to just wrap our function into custom function which is implemented on top of `setTimeout()`


### Have you ever work around closure concept of Javascript ?
if no then this might look confusing...


### Step 1 : Main body of our wrapper function. 
```
function throttle(func, delay) {
    return function (...args) {
        return func(...args);
    };
}
```


we will call this wrapper function like this :
```
function callApi() {
   // here comes the api call logic or any work you want to throttle.
}

const throttledFunction = throttle(callApi, 3000) // 3 in seconds
```


### Step 2 : Now we add timer to this function ⏰
- In next step we will understand why we are getting this timestamp.

```
function throttle(func, delay) {
    return function (...args) {
        const now = new Date().getTime(); // getting the timestamps

        return func(...args);
    };
}
```


### Step 3 : Some logic 
- In here we have something interesting. I mean how do we compare old time with new one ? we probably need some logic right ?
- so here the actual part which is helping the wrapper function to call our passed function only and only if certain delay is passed.
- We have to keep track of `lastCall` which is initially **0**.
- we update this lastCall every time with current time, in our case we set it with `now`.

```
function throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
        const now = new Date().getTime(); // getting the timestamps
        lastCall = now;
        return func(...args);
    };
}
```


### step 4 : Putting some condition which adds throttle behaviour
- we must have to compare our old time and new timer with passed `delay` time and if it is less than passed `delay` time then we have to return our function right away so out actual function will not call this time. 
- it will wait for another time when this throttled function fires.

```
function throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
        const now = new Date().getTime(); // getting the timestamps
        if(now - lastCall < delay) {
          return;  
        }

        lastCall = now;
        return func(...args);
    };
}
```

**_NOTE_**: Sometime you might mess up around comparing timing in `if` statement so i would suggest you to wrap your subtraction line with `abs(now - lastCall) < delay` So we are on same line.


**TIP of the day 💡** : Its always good idea to write readable code so i would highly prefer you to give appropriate name and naming convention should be constant to your entire code base.


### Conclution 🍫 🍩
Yo buddy, **Congratulations ! 🎉**  you just made your own throttling function. Go and use it in your code base.


Reach out to me if you have any queries. I would love to answer you questions.