preface
First of all, it’s important to understand that both anti-shake and interception are used in high-frequency asynchronous firing scenarios, so that the event only fires once. For example, the button continuously submits forms (asynchronous operation), the scroll bar pulls up to load data (asynchronous operation), the input box search association (asynchronous operation) and so on. The difference between anti-shake and interception lies in whether to execute immediately after the event is triggered for the first time by a high frequency click and the reaction after the event is triggered again. Remember whether the first event takes effect, or whether it takes effect later, and you can straighten out the difference between anti-shake and interception.
Debounce
The event is delayed n seconds after it is triggered. If it is triggered again within n seconds, the timer is reset. The last event is executed after n seconds.
Consider how to write code from the definition of anti-shake:
- Execution after n seconds delay (with timer)
- N seconds trigger, re-timing (the second trigger event, the timer will be cleared)
function debounce(fn, delay) {
let timer; // Timer object
return function(. args) {
// 2. If the timer object exists, clear the timer again
timer && clearTimeout(timer);
// 1. Master logic, n seconds later
timer = setTimeout(() = > {
fn.apply(this, args); // Todo: Execute your function
timer = null; },delay); }}Copy the code
Throttle
The event is executed immediately after it is triggered. If the event is triggered within n seconds, it does not take effect. Personal understanding: N seconds after the first event is executed, it can be executed again.
Consider how the code should be written from the definition of interception:
- The event is executed immediately after it is triggered
- Trigger within n seconds, does not take effect (compare the current time with the previous time, whether it takes n seconds to trigger and take effect after n seconds)
function throttle(fn, delay) {
// The current time is now, the delay time is delayed, and the last time is last
let last = 0;
return function(. args) {
const now = +new Date(a);// Get the current time
// 1. Execute the function immediately after the event is triggered. The first now-last is always greater than the delay time
// 2. Compare the time of the two events before and after, and check whether the set delay time has passed.
if(now - last > delay) {
last = now;
fn.apply(this, args); // Todo: Execute your function}}}Copy the code
Application scenarios
Image stabilization
- Search, type in Association
- The window triggers resize, and the window size changes
River closure
- Form submission, button click
- Scroll up to load