The throttle

Throttling is performed immediately; Application scenario: When a rolling event initiates a network request, users are not expected to send requests all the time when rolling, but to send a request at a fixed interval.

const throttle = (fns, wait = 50) { let lastTime= 0; return function (... args) { let now = new Date(); if (now - lastTime > wait){ lastTime = now; fns.apply(this, args); }}}Copy the code

Image stabilization

Anti-shake is not performed immediately;

If the frequency is high all the time, it might only respond the last time;

Application scenario: When a button is clicked consecutively, the request is not executed each time. Instead, the request is triggered when the user clicks the button for a period of time and does not click again

Const debounce = (fn, await)=>{// Cache timer id let timer = 0; // If a timer has been set, empty the previous timer // Start a new timer, delay the execution of the method passed by the user return function (... args) { if (timer) clearTimeout(timer); timer = setTimeout(()=>{ fn.apply(this, args); }, await); }}Copy the code