Home » Tutorials » JavaScript » Optimize Scrolling Performance by Debouncing Scroll Event Calls

Optimize Scrolling Performance by Debouncing Scroll Event Calls

Optimize Scrolling Performance by Debouncing Scroll Event Calls

If you attached a scrolling event to an element and scroll down 1000px, you’re likely to see 100+ events be fired. Such cases are happened commonly in parallax site. If your scroll event handler does a bunch of calculation works, you will see your page become slow, janky & less responsive on less powerful mobile devices. See the bad example here.

To improve the scrolling performance, you have to limit down the rate of scroll event being fired. Here’s an example:

jQuery

var debounce_timer;

$(window).scroll(function() {
	if(debounce_timer) {
		window.clearTimeout(debounce_timer);
	}

	debounce_timer = window.setTimeout(function() {
		// run your actual function here
		console.log('Fire');
	}, 100);
});

The code above shows that the actual callback function in the scrolling event will be fired after 100ms. If a scroll event is fires again & the pending timeout (100ms) has not passed yet, it will clear the pending timeout and reset it again.

Following is another way we wrote it in vanilla JS.

Vanilla JavaScript

var debounce_timer;
window.onscroll = function(){
	if(debounce_timer) {
		window.clearTimeout(debounce_timer);
	}

	debounce_timer = window.setTimeout(function() {
		// run your actual function here
		console.log('Fire');
	}, 100);
};

To see how we limit down the rate of scroll event being fired, please check out the makeover result here.


Android, iOS Development Tutorials