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(); } } }
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)
- 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!

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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

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.

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 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.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use