JavaScript Debounce Function

JavaScript Debounce Function

The absence of the debouncing feature is one of the main errors I see when trying to simplify the existing code. When your web app uses JavaScript to perform taxing tasks, a debounce feature is necessary to ensure that a task is not fired so often that it bricks the performance of the browser.

For those of you who don’t know what a function of debounce does, it restricts the pace a function will fire at. A quick example: on the window, you have a resize listener doing some calculations of element dimensions and (possibly) repositions of a few elements. That’s not a heavy job in itself, but having been shot repeatedly after multiple resizes can slow down your site. Should not limit the function’s rate of fire?

Here’s the basic JavaScript debounce function (as taken from Underscore.js):

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

You will pass the function to execute the debounce, and the limit of the fire rate in milliseconds. Here’s a useful example:

var myEfficientFn = debounce(function() {
	// All the taxing stuff you do
}, 250);

window.addEventListener('resize', myEfficientFn);

The above function will only fire once every quarter of a second, instead of as fast as it is triggered; in some cases, an incredible performance boost.

I’m sometimes asked what rate to use when debouncing and it’s difficult to answer that question because it depends on the task. The easiest way to learn is to search at various levels and see if you find a lag— if you spot it, your users would like that!

Stay Tuned with ci3school.com

Leave a Reply