Vortic
Vortic

Reputation: 75

Performance - window.onscroll vs setInterval

What would be better solution performance-wise - executing a function every 100 ms via setInterval or executing a function when page is scrolled? I just checked and single scroll can cause a function to be executed over 50 times. Setting setInterval to 100ms would cause function to be executed only 10 times per second but on the downside the function would be executed even if the page is not scrolled.

The function is rather simple (checkes window.pageYOffset and changes style if it's over 100)

Upvotes: 1

Views: 1863

Answers (1)

roger
roger

Reputation: 1141

This sounds like a job for a debounce function. Such a method rate limits calls to a function.

You mention the single scroll hitting your callback over 50 times. By utilizing debounce the callback would not be invoked until the debounce function IS NOT called for a specified amount of time. (in the below example 300ms)

var scrollHandler = debounce(function() {
    // your window.pageYOffset logic
}, 300);

window.addEventListener('scroll', scrollHandler);

A much more complete explanation and example debounce function can be found at:

https://davidwalsh.name/javascript-debounce-function

or

Can someone explain the "debounce" function in Javascript

Using such an approach will make a more optimized number of calls, and only when the page is interacted with (sounds like this should happen when the page is scrolled).

Upvotes: 3

Related Questions