Throttling Function in JavaScript

Jagathish Oct 12, 2023
Throttling Function in JavaScript

This tutorial teaches how to add throttling to a function in JavaScript.

Adding Throttling in JavaScript

We can limit the number of times a resource is accessed in a specific time limit through throttling.

For example, we are configuring a function to be invoked only 10 times in one minute. The execution should be blocked when we invoke more than 10 times.

For implementing the throttle, we will maintain the below data:

  • Variable to maintain the maximum number of times the function is invoked.
  • Variable to maintain the timeframe (like 1 minute).
  • Variable to maintain last time at which the method is invoked.
  • Variable to maintain how many times the function is invoked in the current timeframe.

Algorithm of Throttling in JavaScript

When the function is invoked, we will follow the steps mentioned below:

  • Find the time difference between the current time and the last time at which the function is invoked.
    timeDiff = currentTime - lastInvokedTime
    
  • If the time difference is greater than the configured timeFrame, reset the number of times the function invoked in the current timeframe to 0.
    if (timeDiff >= timeFrame) {
      numberOfTimesInvoked = 0;
    }
    
  • Check if the number of times the function is invoked in the current timeframe is less than or equal to the configured number of times a function can be invoked.
    if (numberOfTimesInvoked < numOfTimesFnCanBeInvoked) {
      // invoke the function
    } else {
      // log fn cannot be invoked more than n times
    }
    
  • On invoking the function, we should increment the number of times the function invoked by 1. Also, the last invoked time should be updated to the current time.

Code Sample:

class Throttle {
  constructor(timeFrame, numOfTimesFnCanBeInvoked, func) {
    this.lastInvokedTime = 0;
    this.numberOfTimesInvoked = 0;
    this.timeFrame = timeFrame;
    this.numOfTimesFnCanBeInvoked = numOfTimesFnCanBeInvoked;
    this.func = func;
  }
  call() {
    let currentTime = new Date();
    let timeDiff = currentTime - this.lastInvokedTime;
    if (timeDiff >= this.timeFrame) {
      this.numberOfTimesInvoked = 0;
    }
    if (this.numberOfTimesInvoked < this.numOfTimesFnCanBeInvoked) {
      this.func.apply(this, arguments);
      this.numberOfTimesInvoked++;
      this.lastInvokedTime = currentTime;
    } else {
      console.log(`Trying to call more than ${
          this.numOfTimesFnCanBeInvoked} times within ${this.timeFrame}ms`);
    }
  }
}

The above code will handle the throttling of the function. Let’s create a function and add throttling for that.

function add(a,b){
  console.log(`${a} + ${b} = ${a+b}`);
}

let sum = new Throttle(2000, 2, add) // in 10 sec only two time this method can be called

sum.call(1,2);
sum.call(3,4);
sum.call(5,6); // this will not be executed

setTimeout(()=>{
	console.log("After 2000ms");
	sum.call(5,6); // this will be executed 
	sum.call(7,8);
}, 2000);

Output

1 + 2 = 3
3 + 4 = 7
Trying to call more than 2 times within 2000ms

After 2000ms
5 + 6 = 11
7 + 8 = 15

In the above code,

  • We created a function add.
  • We created a new object for the Throttle class. Configured the add function to be called only two times within 2 seconds.
  • We invoked the add function three times within 2 seconds. For the first two function call, the function will be executed. But for the third function call, the function will not be invoked.
  • We used the setTimeout to call the add function after 2 seconds. The time frame will be new so that the function will be executed.

Related Article - JavaScript Function