Stabilization:
When the event is continuously triggered, the event handler function is called only once. The event will not be triggered within a certain period of time and will be executed only when the event is triggered again.
Application Scenarios:
1. The input box sends ajax requests; 2. Triggered when the window is resize/scrollCopy the code
Implementation:
Cancel the previous setTimeout each time the event is triggered.
function debounce(fn,wait){ let timer=null; return function(){ const that=this; const args=arguments; if(timer){ clearTimeout(timer); } timer=setTimeout(function(){ fn.apply(that,args) },wait); }} function handler(){console.log()}; window.addEventListener("scroll",debounce(handler,1000));Copy the code
Non-immediate execution
function debounce(fn,delay) { let timer = null; return function() { let that = this; let args = arguments; if(timer) { clearTimeout(timer); } timer = setTimeout(function(){fn.apply(that,args)},delay);} timer = setTimeout(() => fn.apply(that, args); // }, delay) } } var clickResult = function() { console.log("debounce!" ); }; var debounceBtn = function() { $("#debounce").click(debounce(clickResult,500)) }; debounceBtn();Copy the code
Executed immediately
function debounce(fn,wait) { let timer=null; return function(){ let that=this; let args=arguments; if(timer){ clearTimeout(timer); } let callNow = ! timer; if(callNow){ fn.apply(that, args) } timer=setTimeout(function(){ timer = null; },wait); } } var clickResult = function() { console.log("debounce!" ); }; var debounceBtn = function() { $("#debounce").click(debounce(clickResult,500)) }; debounceBtn();Copy the code
Throttling:
Causes an event handler to execute once in a certain amount of time when an event is continuously emitted.
Application Scenarios:
1. Click the button many times to take effect once within N seconds; 2. Get the distance of mouse movement (Mousemove); 3, Listen for scroll; 4. DOM element drag (Mousemove);Copy the code
implementation
Each time an event is triggered, determine whether there is a delay function currently.
setTimeout
function throttle(fn,wait){ let timer=null; return function(){ let that=this; let args=arguments; if(! timer){ timer=setTimeout(function(){ fn.apply(that,args); timer=null; },wait) } } }Copy the code
The time stamp
function throttle(fn,wait){ let prev=Date.now(); return function(){ let that=this; let args=arguments; let now=Date.now(); if(now-prev>=wait){ fn.apply(this,args); prev=Date.now(); }}}Copy the code
Example:
</button> function throttle(fn,wait){var timer=null; return function(){ var that=this; var args=arguments; if(! timer){ timer=setTimeout(function(){ fn.apply(that,args); timer=null; },wait) } } } function clickFun() { console.log("hhhhh"); } document.getElementById('clickF').addEventListener("click",throttle(clickFun,1000),false); document.getElementById('clickF').onclick=throttle(clickFun,1000);Copy the code