Javascript function throttling
Posted By : Bhavya Wadhwa | 27-Dec-2014
If we look at the definition of throttle
A device controlling the flow of fuel or power to an engine.
Similarly In Javascript, throttling is a technique by which we rate limit the execution of our functions (which are executed very often ) Or in simpler words, limiting the number of times a function can be executed in a given period of time.
When is this technique useful?
Well, with the help of throttling we can control the rate of execution of function in any situation where functions are called in succession but its mostly used in conjunction with certain Event listeners ( scrolling,keyup,keydown,window resize etc) which can run/ get fired 1.) quite frequently and 2.) have some heavy Event handlers associated with them.
Consider the following scenario’s:
- Scrolling Event : If you have some heavy handler attached to the scrolling event ( which gets fired very rapidly ) like if you are modifying the DOM or trying to fetch the data ( via ajax ) when elements are visible in viewport after scrolling.
- KeyDown Event : If you are planning to create keys shortcuts for your page where you want to jump to some section if press some x key, open a pop up if you press enter key, navigating keys for moving between different cells of a document ( like google spreadsheets ) etc.
In both of the above scenario’s we are bound to have some heavy duty event handlers attached to our listeners and if you are dealing with a application which has a large and complex DOM you should definitely control the rate with which your handler functions will get executed i.e throttle you handler functions.
Implementation:
There are a few ways in which we can implement our throttling function but i’ll try to cover the easiest one:
//global variables
var currentTime,lastTime,delayFnCall,
//timegap decides our throttling rate
// (i.e our handler is executed after every 300ms no matter how many time it executes in between )
timeGap = 300;
//listener
window.addEventListener('scroll',function(){
normalScroll(e);
//passing controlled scroll handler as a argument to throttling function along with other arguments
simpleThrottle(controlledScroll,e);
},false);
//Controlled Scroll Handler
function controlledScroll(e){
console.log('scrolling with throttle');
}
//normal scroll handler ( handler which is not throttled )
function normalScroll(e){
console.log('normal scrolling');
}
//throttling function
function simpleThrottle(fn,args,scope){
var context = scope || this;
currentTime = +new Date();
if (lastTime && currentTime < lastTime + timeGap ) {
clearTimeout(delayFnCall);
delayFnCall = setTimeout(function (){
lastTime = currentTime;
fn.apply(context,args);
}, timeGap );
}
else {
lastTime = currentTime;
fn.apply(context,args);
}
}
Just copy the whole code and run it on your browser's console. After doing so, just scroll over the document and observe the console then you can easily note the difference in the rate of execution of controlled scroll and normal scrolling function.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Bhavya Wadhwa
Bhavya is a lead full stack developer with expertise in Javascript frameworks like AngularJS , NodeJS etc.