function throttling
When an event is continuously triggered, it is guaranteed that the event processing function is only called once within a certain period of time. The popular understanding is that the bus leaves every 20 minutes, regardless of how many people are waiting to board the bus at the bus station during these 20 minutes. So the so-called throttling
is Refers to continuously triggering events but only executing the function once within n seconds. Throttling will dilute the execution frequency of the function.
Code implementation
ps: For throttling, there are generally two ways to achieve it, namely timestamp and timer version.
timestamp version
function trottle(doSomeThing,wait) {
var _this,
_arguments,
initTime = 0;
return function(){
var now = +new Date();
_this = this;
_arguments = arguments;
// 当间隔时间大于一定的时间后才触发对应的函数
if(now - initTime>wait){
doSomeThing.apply(_this,_arguments);
initTime = now;
}
}
}
timer version
function throttle(doSomething,wait){
var timeout;
return function(){
var _this = this;
_arguments = arguments;
//初始timeout是undefined
if(!timeout){
timeout = setTimeout(function(){
// 主要是让每次move的时候,使!timeout为true,直到一段时间后timeout=null
timeout = null;
doSomething.apply(_this,_arguments);
},wait);
};
}
}
function anti-shake
When tasks are triggered frequently, a callback will be executed after an event is triggered for a period of time. If it is triggered again during this period, the timing will be restarted. In layman's terms, it is like getting on an elevator. As long as the elevator door is closed, If someone gets on the elevator during the process, the elevator door will reopen. It will only start running if no one gets on later.
Code
function debounce(fn, wait){
let timer = null
return function(){
let args = arguments
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, wait)
}
}
Common application scenarios
Function anti-shake application scenarios:
Continuous events only need to trigger a callback scenario:
- Search input in the search box, you only need to complete the last input before sending the request
- Phone number. Email verification input detection
- Window size resize only needs to calculate the window size after the window adjustment is completed to prevent repeated rendering.
Application scenarios of function throttling:
Scenarios where a callback is executed at intervals of an event include:
- Scroll to load a long list and listen for scrolling to the bottom of the page
- Google search box, search for Lenovo
- High-frequency click submission and repeated submission of forms
- Repeated requests for some interfaces