All Javascript apps need event throttling!!!
Tags: javascript, webdev, coding, todayilearned
Published: 2020-06-19 10:18:39

---
title: All Javascript apps need event throttling!!!
published: true
description: The simplest way to describe event throttling in javascript and it's application uses.
tags: javascript, webdev, coding, todayilearned
cover_image: https://nimblewebdeveloper.com/static/e4f2960a9ebcff599e4a047f2c2e55b2/ee604/a13dd383a04d91bedde69deadebd77338dd346f4-1200x630.png
---

Did every keypress in the search bar need an API call? how scroll or resize event can be optimized? Such questions are common in platforms like StackOverflow, GitHub, etc.

Google these questions only when we are at the middest of an optimization phase of our application or we are really be sucked at a never-ending API call loop. am I right?

All the google searches are pointing to two major terms in Javascript programming - __Throttling__ and __Debouncing__

Did we need to learn these? yes! Almost all web applications need these techniques to optimize performance. 

Simply __Debouncing__ and __Throttling__ techniques are used to limit the number of times a function can execute. 

Consider a search bar in a shopping cart application, when we type each letter in the field, each time an API call is requested to the server. When we look into the network section in the browser,
there seems to be a number of pending API calls in the list.

Think about it? is this ok for your application?? Really Nope!!!
then the question arises - how to reduce the API calls in a search bar...Yes!! At last, you google it and all the search results repeatedly say- use Throttling and Debouncing buddy...!!!


# Event Throttling
>_Throttling is a technique in which no matter how many times users fires the event, the attached function will be executed only at a regular interval._ 

Actually _Throttling_ is a simple technique , that we can create using the `setTimeout` function in Javascript.

### setTimeout function
`setTimeout` is a `webAPI` provided by the browser and used as a scheduling function in Javascript. Using this function we can delay an event or function call to a period of time.

The syntax is:
``` javascript
let timerId = setTimeout(callbackFunction, timeToDelay);
```

Here the __callbackFunction__ defines the code that needs to be executed after the __timeToDelay__ period of time.

The `setTimeout` function will return a __timerId__, which is a positive integer value to uniquely identify the timer created by the call to `setTimeout`.This value can be passed to `clearTimeout` to can the timeout.

>_Remember, the **timerId** is the key point in throttling_.


```javascript
//Example of setTimeout
const showMessage = function() {
console.log('show this message after 2 seconds');
};

let timerId = setTimeout(showMessage, 2000); //the showMessage function will call after 2000 ms and show the message.
```

###Implementation

Throttling will fires the function call attached with it, once in an interval.For the below given example the __scroll__ event will be counted with and without throttling implementation.

####Without throttling

The sample `index.html` file is:

```html
<head>
 <style>
		div {
			border: 1px  solid  black;
			width: 300px;
			height: 200px;
			overflow: scroll;
		}
    </style>  
</head>

<body>
    <div  id="div-body">
        <p style="background-color: red; height: 700px">This is line 1</p>
        <p style="background-color: blue; height: 700px">This is line 2</p>
        <p style="background-color: green; height: 700px">This is line 3</p>
        <p style="background-color: yellow; height: 700px">This is line 4</p>
    </div>
    
    <p>No of times event fired</p>
    <p id='show-api-call-count'></p>

    <script src= "script.js" />
</body>
```

the javascript `script.js` file is:
```javascript

let timerId, eventCallCount;
const divBodyDom = document.getElementById('div-body');

divBodyDom.addEventListener('scroll', function() {
    const eventCallCountDom = document.getElementById('show-api-call-count');
    eventCallCount= eventCallCount|| 0;

    eventCallCount+= 1;
    eventCallCountDom.innerHTML = eventCallCount;

});
```

RESULT: 
![Without throttling](https://www.dropbox.com/s/46xtqaz16686pcq/without-throttling.gif?raw=1)

#### Using Throttling

The sample `index.html` file is:
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Throttling in Javascript</title>

    <style>
		div {
			border: 1px  solid  black;
			width: 300px;
			height: 200px;
			overflow: scroll;
		}
    </style>
    
</head>
<body>
    <div  id="div-body">
        <p style="background-color: red; height: 700px">This is line 1</p>
        <p style="background-color: blue; height: 700px">This is line 2</p>
        <p style="background-color: green; height: 700px">This is line 3</p>
        <p style="background-color: yellow; height: 700px">This is line 4</p>
    </div>
    
    <p>No of times event fired</p>
    <p id='show-api-call-count'></p>

    <p>No of times throttling executed the method</p>
    <p id="debounc-count"></p>

    <script src= "script.js" />
</body>
</html>
```

the javascript `script.js` file is:
```javascript
let timerId, apiCallCount, throttlingDomCount;
const divBodyDom = document.getElementById('div-body');

function makeAPICall() {
    const throttlingDom = document.getElementById('debounc-count');

    throttlingDomCount = throttlingDomCount || 0;
    throttlingDomCount += 1;

    throttlingDom.innerHTML = throttlingDomCount;

}

function throttleFunction(func, delay) {
    if(timerId) {
        return;
    }

    timerId = setTimeout(function() {
        func();
        timerId = undefined;
    }, delay);
}

divBodyDom.addEventListener('scroll', function() {
    const apiCallCountDom = document.getElementById('show-api-call-count');
    apiCallCount = apiCallCount || 0;

    apiCallCount = parseInt(apiCallCount) + 1;
    apiCallCountDom.innerHTML = apiCallCount;

    throttleFunction(makeAPICall, 200);
});

```

Result:

![event-throttling](https://www.dropbox.com/s/mxtprjrqsobkavn/using-event-throttling.gif?raw=1)

##Explanation
Here the _throttle()_ function will handle the _makeAPICall()_ and pass an interval value as 200.
so the _throttle()_ will make an arrangement to trigger the _makeAPICall()_ function in an interval of 200ms.

Inside the _throttle()_ function the main point is the _timerId_.

If the _timerId_ is `undefined`, then the `setTimeout` function will trigger and _timerId_ returns. 

If the _timerId_ is a valid one, that means one `setTimeout` function is pending to complete.right? so it will return without doing anything. That means the _makeAPICall()_ function will be executed only when the _timerId_ is set. That occurs only after completion of each `setTimeout` function.

By setting the passing delay as the delay parameter of the `setTimeout` function, we can execute the _makeAPICall()_ function in a regular interval of 200ms. 

Also, don't forget to reset the __timerId__ to `undefined`, then only the next event trigger will do as our wish.


Really simple..Yeah??

# Conclusion

The developer can control the execution of events with a time interval for like, window resize, repeated button click, speedy search type, mouse move event, etc using Event throttling concept.

How can we do some action only after the completion of an event? - Using __Debouncing()__. Wait for my next blog!!!