Javascript

Creating Throttle Function In JavaScript

What is a Throttle Function? Let us assume a scenario where we need to add an event listener to a DOM element,...

Written by Luci · 1 min read >

What is a Throttle Function?

Let us assume a scenario where we need to add an event listener to a DOM element, say a button. There is a user interaction with the button for a service request, example: – a login button where the user clicks on the login button and sends an Ajax request to validate the credentials given in the inputs. The user can click the button multiple times without waiting for the API to send a valid response.

We need to fix it, right?

Let us find a solution for this in jsfiddle. I have created a DOM element for the button like as follows.

<button id="btn">Click me</button>

In JS, I have written a higher order function for throttling.

const DELAY = 5000;
const btn = document.getElementById('btn');

const throttleFn = (fn, delayTime) => {
	let initialTimeStamp = new Date().getTime();
	let isFirstTimeExecution = true;
	
	return () => {
		if (isFirstTimeExecution) {
			fn();
			isFirstTimeExecution = false;
		}
	
		const currentTimeStamp = new Date().getTime();
		if (currentTimeStamp - initialTimeStamp > delayTime) {
			fn();
			initialTimeStamp = new Date().getTime();
		}
	};
};

btn.addEventListener('click', throttleFn(() => {
	console.log('clicked');
}, DELAY));

The higher order function takes two arguments, one is for the function reference, another is the delay time. We are creating a lexical scope in the higher order function for keeping the execution state. It will tell us whether the callback is done or not.

The throttle function will not execute the callback reference if it is triggered and the delay time is not over yet. Once the delay time is over, it accepts next callback reference.

So, we can use a throttle function to resolve this problem. We can also resolve this issue by debounce time. We will discuss on this in another post.

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x