What is anti – shake and throttling
Ps: For example, in the search box, the user uses the change event to call the search when entering. If the user enters every time to search, how much server resources will be consumed. Even if your server resources are very powerful, it does not take so to play.
1. Resist – debounce
One solution is to search for a String every time the user stops typing after a delay of more than 500ms. This is anti-shake.
- Principle: Combine several function calls into a single call that is called only once after a given time has passed.
- Code implementation:
function debounce(fn, delay) {
// Maintain a timer to record the state of the currently executing function
let timer = null;
return function() {
// Get function scope and variables with 'this' and' arguments'
let context = this;
let args = arguments;
// Clean up the function being executed and re-execute it
clearTimeout(timer);
timer = setTimeout(function() { fn.apply(context, args); }, delay); }}let flag = 0; // Count the number of current function calls
// The function that is called when the user scrolls
function foo() {
flag++;
console.log('Number of calls: %d', flag);
}
// Wrap our function in debounce, firing every 2 seconds
document.body.addEventListener('scroll', debounce(foo, 2000));
Copy the code
debounce
After the function is wrapped, the inner function is returned- Each time an event is triggered, the current one is cleared
timer
Then reset the timeout and call. This causes each high-frequency event to cancel the previous timeout call, and the event handler cannot be fired- Only when the high frequency event stops can the timeout call triggered by the last event be called
delay
Execution after time
2. Throttle
The other solution is a bit looser than the anti-shake solution, where we don’t want the user to just type, but to give the user some search hints, so we limit the query to String every 500ms. This is throttling.
- How it works: The throttling function guarantees that a real event handler will be executed within a specified period of time, no matter how frequently events are triggered.
- 1) Time stamp implementation:
function throttle(func, delay){
let prev = Date.now();
return function(){
const context = this;
const args = arguments;
const now = Date.now();
if(now - prev >= delay){
func.apply(context, args);
prev = Date.now(); }}}Copy the code
When a high frequency event is triggered, it should be executed immediately for the first time (if the interval between the event binding function and the actual event is greater than delay) and every delay second after that, no matter how frequently the event is triggered. When the last event is triggered, the event will not be executed.
2) Timer implementation: When the event is triggered, we set a timer. When the event is triggered again, if the timer exists, it will not be executed. After delay seconds, the timer executes the execution function to clear the timer so that the next timer can be set.
fucntion throttle(func, delay){
let timer = null;
return funtion(){
let context = this;
let args = arguments;
if(! timer){ timer = setTimeout(function(){
func.apply(context, args);
timer = null; }, delay); }}}Copy the code
When the event is first raised, the function is definitely not executed immediately, but after a delay of seconds. After that, events will be continuously triggered and executed once every delay second. After the last stop, the function may be executed again due to timer delay.
3) Integrated use of timestamp and timer, the completion of an event trigger immediately executed, trigger can be executed once the throttle function
function throttle(func, delay){
let timer = null;
let startTime = Date.now();
return function(){
let curTime = Date.now();
let remaining = delay - (curTime - startTime);
const context = this;
const args = arguments;
clearTimeout(timer);
if(remaining <= 0){
func.apply(context,args);
startTime = Date.now();
}else{ timer = setTimeout(func, remaining); }}}Copy the code
The function must be executed once in each delay time. Therefore, the start time, current time, and delay are used in the throttling function to calculate remaining. When remaining <= 0, the function is executed. Of course, if the remaining event occurs again, the timer is cancelled and a remaining is recalculated to determine the current state.