What is throttling in JavaScript?

aamchora

Hemendra Khatik

Posted on June 30, 2022

What is throttling in JavaScript?

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

let me help you

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

Unlike Debouncing, 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,

<!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>
Enter fullscreen mode Exit fullscreen mode
let count = 0;
function submitData(query){
   // some api call
   console.log("result",count++)
}

document.querySelector(".btn").addEventListener("click",()=>{
submitData();
})
Enter fullscreen mode Exit fullscreen mode

first example

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.

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);
Enter fullscreen mode Exit fullscreen mode

second

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 || Linkedin

💖 💪 🙅 🚩
aamchora
Hemendra Khatik

Posted on June 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related