Thursday, July 28, 2016

Quick Tip: How to Throttle Scroll Events

One of the perils of listening to scroll events is performance degradation. The browser will execute the callback every single time the user scrolls, which can be many events per second. If the callback performs a bunch of repaints, this means bad news for the end user. Repaints are expensive, especially when you are redrawing large parts of the view, such as is the case when there is a scroll event.

The example below illustrates the issue:

See the Pen Unthrottled Scroll Events by SitePoint (@SitePoint) on CodePen.

Apart from performance degradation and being prone to causing seizures. This example illustrates what happens when the computer does exactly what you tell it to do. There is no smooth transition between background colors and the screen just flickers. Any hapless programmer may feel as if there is no hope left in this world. Isnʼt there a better way?

Regulating Events

One solution is to defer events and manage a bunch of them at once. There are two commonly used functions that can help us with this: throttle and debounce.

Throttle guarantees a constant flow of events at a given time interval, whereas debounce groups a flurry of events into one single event. One way to think about it is throttle is time-based and debounce is event driven. Throttling guarantees execution while debounce does not once grouping has occurred. If you want to know the specifics, check out this in-depth discussion of debounce versus throttling.

Debounce

Debounce solves a different problem, such as key presses with Ajax. When you type in a form, why would you send a request per keystroke? A more elegant solution is to group a burst of keystrokes into one event that will trigger the Ajax request. This fits within the natural flow of typing and saves server resources. With key presses, the interval between events isn't important, since users donʼt type at a constant rate.

Throttle

Since there are no guarantees with debounce, the alternative is to throttle the scroll events. Scrolling occurs on a given time span, so it is fitting to throttle. Once the user begins scrolling, we want to guarantee execution on a timely basis.

This technique helps with checking if we are at a specific part of the page. Given the size of the page, it takes many seconds to scroll through content. This enables throttling to fire the event only once at any given interval. Event throttling will make the scrolling experience smoother and guarantee execution.

Below is a poor manʼs event throttler in vanilla JavaScript:

Continue reading %Quick Tip: How to Throttle Scroll Events%


by Camilo Reyes via SitePoint

No comments:

Post a Comment