There are some events that can be triggered far more frequently than you might expect. Events such as scroll, resize, keypress and keyup (as well as others) can be triggered over and over again with a single action (for example dragging with the mouse or holding down a key on the keyboard).

The debounce function provides us with a way to limit how frequently the functions we attach to these events can be triggered.

When the debounce function is called it returns a version of the function passed to it that has been made more efficient in that the actual function code will be delayed and then subsequent calls to the function during the delay will just restart the delay so that the processing for the event can only happen once when it is triggered at more frequent intervals than the specified delay amount.

Setting the optional third parameter to debounce to true allows you to bypass the debounce processing without having to rewrite the code to remove the debounce.

Here's the debounce function which I have modified slightly so that it is written the way that I would have written it.

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
        var context, args, later, callNow;
		context = this;
        args = arguments;
		later = function() {
			timeout = false;
			if (!immediate) func.apply(context, args);
		callNow = immediate && !timeout;
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);

To use debounce we simply simply wrap our original function code inside of a call to debounce and specify the delay period as the second parameter. So if our original call is:

var myFn = function() {
	// function code goes here
window.addEventListener('scroll', myFn);

We simply add the debounce wrapper like this:

var myFn = debounce(function() {
	// function code goes here
}, 250);
window.addEventListener('scroll', myFn);


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow