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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles