Scenarios and requirements for the occurrence of the anti-shake function: When an event, such as clicking a button or scrolling or zooming a browser, triggers the callback function multiple times within a specified period of time, execute the callback function only once

Actual case: For example, in the process of payment, when the user clicks the payment button for several times and initiates the successful payment request within the specified actual time, each order should only be successfully paid once

const button = document.querySelector('button'); // let payMoney = function payMoney(){console.log(' click to effect '); // Print this context for calling this function and payMoeny's arguments console.log(this,arguments); } function debounce(func, delay = 100){// Define a timer outside the closure. return function(){ let context = this; let args = arguments; // Each click clears the assignment of the previous click (before the specified time) Timer clearTimeout(Timer); // 2. Each time the anonymous function checks to see if the local execution context has a reference to the timer. If not, look up the execution context (external function debounce) at the next level. Timer = setTimeout(()=>{func.call(context, args); // Every time the business code is successfully called, empty the reference to timer, so as not to cause memory leak timer = null; }, delay); // If the internal function calls the external function variable, set it to null to prevent memory leakage. Internal functions have references before them and should be actively destroyed.) // 3 This cannot be null, because a timer is referenced to the execution context one level up each time, in the same way that let timer is defined within an internal anonymous function, // 3. // Timer =null; // Timer =null; // Timer =null; }} // 1. Add an anti-shock callback for the click event, debounce actually executes the context of the anonymous function (each function has its own context, The largest is the global context) button.addeventListener ('click',debounce(payMoney, 1000));Copy the code

— — — — — — — — — — — — — — — — — — — — –

Vue project implementation is shock-proof (confused: why can’t you set the return internal anonymous closure function in the method?)

export default{ ... data(){ return { ... timer: null; }; },... methods:{ submitDebounce(){ clearTimer(this.timer); This.timer = setTimeout(() => {// business code this.subaddr (); timer = null; })}}}Copy the code