One, realize the anti-shake function
The principle of the anti-shake function: the callback is executed n seconds after the event is triggered, and if it is triggered within these n seconds, the timing will be restarted.
Handwritten simplified version:
// 防抖函数
const debounce = (fn, delay) => {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args); }, delay);
};
};
Applicable scene:
- Button submission scenario: Prevent multiple submission buttons and only execute the last submission.
- Server-side verification scenario: Form verification requires the cooperation of the server-side. It only performs the last time of a continuous input event, and it also has a similar function of searching for associated words.
Supplement: (please use lodash.debounce for living environment)