Code Implementation
function debounce(fn,delay){
let timerId;
return function(...args){
clearTimeout(timerId);
timerId=setTimeout(()=>{
fn.apply(this,args);
},delay);
};
}
//usage
const d_layout = debounce(layout,500);
window.onresize = d_layout;
In JavaScript, the debounce function is a core tool for optimizing high-frequency and time-consuming operations. Its core logic lies in delaying function execution while canceling repeated delays. This ensures that when a function is triggered multiple times within a short period, it will only execute after waiting for a specified delay following the last trigger. This avoids performance overhead caused by unnecessary invocations.
The working principle can be analogized to "an elevator closing its doors": After an elevator opens, it waits for a fixed period (e.g., 2 seconds) by default before closing. If a new passenger enters during this waiting period (corresponding to a new trigger of the function), the original waiting timer is canceled and the countdown restarts. Only when no new triggers occur after the countdown ends will the "door-closing" action (corresponding to the function execution) take place.
Snippet Description
Applicable Scenarios
- High-frequency triggering: The function is called repeatedly within a short time (e.g., window resize events, input field input events). This is not limited to DOM events; it also applies to high-frequency function calls in non-DOM environments (such as Node.js).
- Time-consuming functions: The called function is either CPU-intensive (e.g., page layout calculations, extensive DOM operations that cause reflows/repaints) or IO-intensive (e.g., network requests, file reading/writing). Simple operations (such as calculating 1+1) do not require debouncing.
- Final trigger result priority: Among the results of multiple calls within a short time, only the result of the last call needs to be retained. For example, after adjusting the window size, only the layout corresponding to the final size is necessary—layouts generated during the adjustment process are irrelevant.
Recommended Snippets
Hello World
PHP Hello World Example,PHP is a server-side scripting language, mainly used for web development, can be embedded in HTML
Hello World
Kotlin Hello World Example, Kotlin is a modern JVM language developed by JetBrains and one of the preferred languages for Android development
Hello World
Perl Hello World Example, Perl is a powerful text processing language, known for its flexibility and rich regular expression support