Key Points
This article was reviewed by Vildan Softic and Julian Motz. Thanks to all SitePoint peer reviewers for getting SitePoint content to its best!
One of the dangers of listening to scroll events is performance degradation. The browser executes a callback function every time the user scrolls, which can have many events per second. If the callback function performs a lot of redraw operations, this means bad news for the end user. Redrawing is expensive, especially when redrawing most of the view, such as when a scroll event occurs.
The following example illustrates this problem:
View example on CodePen: Unthrottling scrolling events
In addition to performance degradation and prone to seizures. This example illustrates what happens when the computer follows exactly your instructions. There is no smooth transition between background colors, the screen just flashes. Any unfortunate programmer may feel that there is no hope in this world. Is there no better way?
Standard Events
One solution is to postpone events and manage multiple events at once. There are two commonly used functions that can help us do this: throttling and debounce.
Trust ensures a constant flow of events over a given time interval, while de-bumping combines a series of events into a single event. One way of thinking is that throttling is based on time, while debounce is based on event. Throttle is guaranteed to be executed, while de-jitter is not guaranteed to be executed after the packet occurs. If you want to know more about this, please check out this in-depth discussion on de-bumping and throttling.
De-shaking
Debounce solves different problems, such as buttons with Ajax. Why send a request for each keypress when you type something in a form? A more elegant solution is to combine a series of keys into one event that will trigger an Ajax request. This conforms to the natural process of typing and saves server resources. For key presses, the interval between events is not important because the user does not type at a constant rate.
Trust
As there is no guarantee of debounce, another method is to throttle the rolling event. The scrolling occurs within a given time span, so it is appropriate to throttle. Once the user starts scrolling, we want to ensure timely execution.
This technique helps check if we are located in a specific part of the page. Given the size of the page, it takes many seconds to scroll through the content. This allows throttling to trigger events only once within any given interval. Event throttling will make the scrolling experience smoother and ensure execution.
The following is a simple event throttle written in native JavaScript:
function throttle(fn, wait) { var time = Date.now(); return function() { if ((time + wait - Date.now()) < 0) { fn(); time = Date.now(); } } }
This implementation sets a time variable that tracks the moment when the function is first called. Each time the returned function is called, it checks if the waiting interval has passed, and if so, it triggers the callback and resets the time.
View the example on CodePen: Native JS throttling implementation
User library
There are many dangers in event throttling, and it is not recommended to write it yourself. Rather than writing your own implementation, I recommend using a third-party implementation.
lodash
lodash is the de facto standard for event throttling in JavaScript. This library is open source so you can browse the code as you like. The benefit is that the library is modular, so you can get what you want from it.
Using lodash's throttling function, rolling event throttling becomes simple:
window.addEventListener('scroll', _.throttle(callback, 1000));
This limits the incoming rolling event torrent to once every 1000 milliseconds (one second).
TheAPI provides front- and back-edge options as follows:
_.throttle(callback, 1, { trailing: true, leading: true });
These options determine whether the callback function is executed at the front and/or the back edge of the event.
One problem here is that if you set both the front and the back edge to false, the callback function will not fire. Setting the front edge to true will immediately start the callback execution and then throttling. This ensures execution for each interval when you set both the front and trailing edges to true.
View the demo on CodePen: Throttle Rolling Event
From looking at the source code, I found interesting that throttle() is just a wrapper for debounce() . Throttle is simply passing a different set of parameters to change the desired behavior. Throttle sets a maxWait, which will guarantee execution once you wait for this long. The rest of the implementation remains the same.
I hope you find lodash good for you in your next event throttling adventure!
Conclusion
The key to throttling and debounce is to check the nature of the problem to be solved. These two technologies are suitable for different use cases. I suggest looking at the question from the user's perspective to find the answer.
The advantage of using lodash is that it abstracts a lot of complexity in a simple API. The good news is that you can use _.throttle()
in your project without adding the entire library. There is lodash-cli, a tool that allows you to create only custom builds containing the required functions. Event throttling is only a small part of the entire library.
FAQs about throttling rolling events (FAQ)
Trust rolling events in JavaScript is a technology used to optimize the performance of a website or web application. When a user scrolls on a web page, the browser generates a scroll event for each pixel's movement. This can result in hundreds or even thousands of events generated per second, which can severely degrade the performance of the web page. By throtting these events, we can limit the number of events to be processed, thereby improving web page performance and responsiveness.
Trust in JavaScript works by setting a delay between event executions. When an event is triggered, the timer starts. If another event is triggered before the timer ends, the event is ignored. This ensures that a certain amount of time must pass before another event is processed. This technique is especially useful for frequently triggered events such as scrolling events.
Trusting and debounce are techniques used to limit the number of times a function can be executed over time. The main difference between the two is how they handle latency. Throttle ensures that the function is not called more than once every X millisecond, while debounce ensures that the function is not called until X milliseconds have elapsed since the last call. In other words, throttling executes the function at regular intervals, while debounce executes the function after a period of inactivity.
The setTimeout
function can be used to throttle in JavaScript. This function allows you to delay the execution of the function by a specified number of milliseconds. By using setTimeout
with event listeners, you can ensure that the event handler function is not called more than once every X milliseconds.
Yes, throttling can be used with any type of event in JavaScript, not just scrolling events. It is especially useful for events that often trigger or require extensive processing, such as mouse movement events, resize events, and key press events.
Yes, there are several libraries and frameworks that provide built-in support for throttling. For example, the popular JavaScript utility library Lodash provides a throttling function that makes it easy to implement throttling. Similarly, the popular JavaScript library jQuery also provides a throttling function in its API.
While throttling can improve the performance of a web page, it can also lead to slow user experience response if used improperly. For example, if the delay is set too high, users may notice a lag between their operations and the response of the web page. Therefore, it is important to find a balance between performance and response speed when using throttling.
You can test the effectiveness of throttling by measuring the performance of the web page before and after throttling. This can be done using browser developer tools, which provides detailed information about web page performance, including the time it takes to process events.
Yes, throttling can be used in combination with other performance optimization techniques such as debounce and requestAnimationFrame
. By combining these technologies, you can further improve the performance and responsiveness of your web pages.
Yes, there are several alternatives to throttling, including debounce and requestAnimationFrame
. Debounce is similar to throttling, but instead of limiting the number of times a function can be called over time, it ensures that the function will not be called until a certain time has passed since the last call. requestAnimationFrame
is a method that tells the browser to execute an animation and requests the browser to call a specified function to update the animation before the next repaint.
The above is the detailed content of Quick Tip: How to Throttle Scroll Events. For more information, please follow other related articles on the PHP Chinese website!