Description: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated

Cancel the previous delayed call method each time an event is raised

function debounce(fn) { let timeout = null; Return function () {clearTimeout(timeout); return function () {clearTimeout(timeout); SetTimeout = setTimeout(() => {// Then create a new setTimeout, This ensures that the fn function fn.apply(this, arguments) will not be executed if more characters are entered within the interval after the input; }, 500); }; } function sayHi() {console.log(‘ console.log ‘); }

var inp = document.getElementById('inp'); inp.addEventListener('input', debounce(sayHi)); / / image stabilizationCopy the code

2 the throttling is false for 500 ms, will not start the request, intercepted, the throttling interprets the high frequency event firing, but will only execute once in n seconds, so the throttling will dilute the execution frequency of the function

Each time an event is triggered, it determines whether there is a delay function waiting to be executed

function throttle(fn) { let canRun = true; Return function () {if (! canRun) return; // Check whether the flag is true at the beginning of the function, otherwise return canRun = false; SetTimeout (() => {fn.apply(this, arguments); // Finally, set the flag to true after setTimeout (critical) to indicate that the next loop can be executed. The flag is always false when the timer is not executed and is returned at the beginning. CanRun = true; }, 500); }; } function sayHi(e) { console.log(e.target.innerWidth, e.target.innerHeight); } window.addEventListener(‘resize’, throttle(sayHi));