Original Article Link
This document explains how to improve animation performance using throttle in JavaScript and applies throttle to solve the issue of choppy scroll animations. It also compares the differences before and after applying throttle.
Throttle is a technique that limits a function to be called 'at most once' within a 'certain time interval'. In other words, even if an event occurs multiple times within a short period, the function will only be executed once within the time interval set by the throttle. For example, if a function has a throttle of 100ms, even if the event occurs 10 times in 1 second, the function will be executed a maximum of 10 times (at 100ms intervals).
Throttle can be used in the following situations:
An attempt was made to implement a smooth scroll animation according to the scroll wheel event, but before applying throttle, the animation was choppy.
Reason: This is because the wheel event occurs at a very high rate, causing the window.scrollBy function to be called excessively, preventing the browser from processing all requests.
useEffect(() => { const container = scrollContainerRef.current; if (!container) return; const handleWheel = (event) => { event.preventDefault(); window.scrollBy({ left: event.deltaY, behavior: 'smooth' }); }; container.addEventListener('wheel', handleWheel); return () => { container.removeEventListener('wheel', handleWheel); }; }, []);
In this code, the handleWheel function is executed every time a wheel event occurs. This function calculates the scroll amount using the deltaY value of the event and scrolls by calling the window.scrollByfunction. The problem is that the wheel event can occur multiple times in a very short period, which causes window.scrollBy to be called excessively, resulting in a choppy animation.
useEffect(() => { const container = scrollContainerRef.current; if (!container) return; const handleWheel = (event) => { event.preventDefault(); window.scrollBy({ left: event.deltaY, behavior: 'smooth' }); }; container.addEventListener('wheel', handleWheel); return () => { container.removeEventListener('wheel', handleWheel); }; }, []);
In the throttled code, the throttleTimer variable is used to manage function execution. The process works as follows:
Initial Delay of setTimeout
setTimeout is used to implement the throttling mechanism. setTimeout executes the callback function after the specified delay (16ms in this case). Consequently, when the first wheel event occurs, window.scrollBy is invoked after a 16ms delay. This initial delay can lead to a perceived lack of immediate responsiveness, potentially being interpreted as stuttering, particularly with rapid wheel movements. (Further improvements will be explored in the future...)
The above is the detailed content of [Translations] Implementing Animations with Throttle in JavaScript. For more information, please follow other related articles on the PHP Chinese website!