Debounce and throttle are both methods to control the frequency of event handling functions. When a function involves DOM manipulation or server requests and is used as a high-frequency event handler, such as the onscroll
event, it's necessary to control the frequency of the event handling function. Otherwise, it may lead to a significant waste of resources and performance degradation. However, whether debounce or throttle, they essentially do not reduce the number of event triggers, but instead improve performance by reducing the execution frequency of event handling functions.
When the event is continuously triggered, the event handling function is not executed at all. It is only executed after a certain period of time after the last trigger ends. The most common example is the search suggestion feature. When the user continuously inputs, the server is not requested to calculate the search suggestions until a certain period of time (N
milliseconds) after the user completes the input and the data is sent to the backend for search suggestions.
Implementation idea: Cancel the previous delayed call method each time the event is triggered and reset the timer.
When the event is continuously triggered, the event handling function is immediately executed, and then the event handling function is not executed again until a certain period of time after the last event trigger.
Implementation idea: Check if the timer exists, if not, execute the event handling function, and then reset the timer regardless of whether the timer already exists.
When the event is continuously triggered, throttle can dilute the frequency of the event handling function. For example, if the onmousemove
event is triggered 100
times within 1
second, through throttling, the event handling function of the onmousemove
event can be executed only 10
times within 1
second, that is, every 100ms
.
Implementation idea: Record the timestamp of the last event handling function execution time. When the event is triggered, if the time difference is greater than the execution period, execute the event handling function and assign the execution time to the current timestamp.
Implementation idea: Check if the timer exists. If not, execute the event handling function and reset the timer.