1. Shake prevention: The function will be 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 will be recalculated
Cancel the previous delayed call method each time an event is raised
Code examples:
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. Throttling: high-frequency events are triggered, but will only be executed once in n seconds, so throttling will dilute the execution frequency of the function
Each time an event is triggered, it will determine whether there is currently a delay function waiting to execute.
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));Copy the code