# What is throttling in JavaScript?

Again a jargonish word, but let me demystify it for you.

![let me help you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rz7pwdqvr8e25wa9sig9.gif)
 

It's nothing but a simple technique we use to prevent unnecessary function calls to improve app's performance.


Unlike [Debouncing](https://aamchora.hashnode.dev/what-is-debouncing-in-javascript), here we block a function call for a particular time if it's been executed recently. Or we could also say that throttling ensures a function call regularly at a fixed rate.


Let's look at the below example,

```html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Throttling</title>
    </head>
    <body>
        <button class="btn">Click here</button>
        <script src="index.js"></script>
    </body>
</html>
```


```js
let count = 0;
function submitData(query){
   // some api call
   console.log("result",count++)
}

document.querySelector(".btn").addEventListener("click",()=>{
submitData();
})
```

![first example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/noojew5jtc2l6uxtze68.png)
 

In the above example, if you click 10 times in 2000ms, Function will be called 10 times, as you can clearly see in the above example. 

It's a very expensive operation, and as dev, our job is to make operations as cheap as possible. 

Let's see how throttling helps us to make these operations cheaper.


```js
function throttle(fn,delay){
  let last = 0;
 /*  
here ...args is optional I've used this in case, if you 
want to pass some parameters you can use ...args
*/ 
  return (...args)=>{
    const now = new Date().getTime();
    if(now - last < delay){
      return;
    }
   last = now;
   return fn(...args)
  }

}

const magicFunction = throttle(submitData,1000);

let count = 0;
function submitData(){
   // some api call
   console.log("result",count++)
}

document.querySelector(".btn").addEventListener("click",magicFunction);
 ```

![second](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owa67zg0804zmsp8ko7e.png)

Now, if you click 10 times in 2000ms, Function will be called 2 times only, as you can see in the code. We have blocked the function call for 1000ms.

_That's how we can implement the **throttling technique** to **improve our app's performance**_

---


_**follow me for more such blog posts.**_

_Let me know if this blog was helpful._

[Twitter](https://twitter.com/AamChora) || [Linkedin](https://www.linkedin.com/in/hemendrakhatik/)

