😃😃😃 my ability is limited, welcome to improve ~
1. Handwriting anti-shock function (debounce)
Anti-shake function function:
The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset.
A search box, for example, doesn’t send requests when the user keeps typing. A request is sent only if the user has not entered anything for a period of time. If the input continues for less than T, the time T is recalculated and the request is not sent. This reduces the number of requests to be sent, improves performance and improves user experience.
Realize the anti-shake function:
// func is a function that the user passes in to be buffed
// wait indicates the waiting time. If no parameter is sent, the default value is 50ms
// Because of the closure, the timer will always be in memory
const debounce = (func, wait = 50) = > {
// Cache a timer
let timer = null;
// Returns the function that the user actually calls each time
return (. args) = > {
// Clear the last timer if it has already been set
if (timer) clearTimeout(timer);
// Start a new timer to delay the execution of the user-passed method
timer = setTimeout(() = > {
func.apply(this, args);
}, wait);
};
};
Copy the code
Effect:
Upper input box, lower display area, continuous input content, the lower display area will not update. The lower display area will update the content only if the content is not entered within 1s.
2. Handwriting throttle
Throttling function functions:
Specifies that a function can fire only once per unit of time. If more than one function is fired in this unit of time, only one function will take effect.
Implement the throttling function:
// func is a function that the user passes in to be buffed
// wait indicates the waiting time. If no parameter is sent, the default value is 50ms
// Falg will always be in memory because of closures
const throttle = (func, wait = 50) = > {
// define falg, initial true
let flag = true;
// The function returned is the throttling function that the user actually calls each time
return (. args) = > {
if (flag) {
// If flag is true, the timer is executed
setTimeout(() = > {
func.apply(this, args);
// After the function completes, change the flag back to true
// For execution next time
flag = true;
}, wait);
}
// Because the timer is an asynchronous task, the flag is disabled immediately after the timer is executed
// While waiting for the delay time, the valve is always closed and the function is not always executed
flag = false;
};
};
Copy the code
Effect:
Upper input box, lower display area. When continuously entering content, the display area below will only update every 500ms.