Home Web Front-end JS Tutorial Quick Tip: How to Throttle Scroll Events

Quick Tip: How to Throttle Scroll Events

Feb 17, 2025 am 10:07 AM

Quick Tip: How to Throttle Scroll Events

Key Points

  • Listening to scroll events can cause performance degradation because the browser executes a callback function every time the user scrolls; throttling and debounce are two common functions to manage this problem. Throttle ensures a constant flow of events over a given time interval, while de-bumping combines a series of events into a single event.
  • Implementing event throttling in JavaScript can be complicated, and it is recommended to use a third-party implementation like lodash, which is the standard for event throttling. Lodash's throttling function simplifies rolling event throttling and provides options to determine whether the callback function is executed at the front and/or back edge of the event.
  • The key to choosing throttling and debounce is to see the nature of the problem to be solved. Throttle applies to events that occur within a given time span, such as scrolling, while debounce applies to events such as key presses, where the interval between events is not important.

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();
    }
  }
}
Copy after login

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));
Copy after login

This limits the incoming rolling event torrent to once every 1000 milliseconds (one second).

The

API provides front- and back-edge options as follows:

_.throttle(callback, 1, { trailing: true, leading: true });
Copy after login

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)

  • What is the purpose of throttling rolling events in JavaScript?

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.

  • How does throttling work in JavaScript?

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.

  • What is the difference between throttling and de-shaking?

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.

  • How do I achieve throttling in JavaScript?

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.

  • Can I use throttling with other events in addition to scrolling events?

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.

  • Is there any library or framework that provides built-in support for throttling?

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.

  • What are the potential drawbacks of throttling?

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.

  • How do I test the effectiveness of 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.

  • Can throttling be used in combination with other performance optimization techniques?

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.

  • Is there an alternative to throttling?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

See all articles