Scenario: Input triggers the change event. When the interface is frequently requested and operations such as window resize, Scroll, and input box content verification are performed, if the frequency of event processing function calls is unlimited, the burden on the browser (server) will be increased, resulting in poor user experience. Debounce and throttle can be used to reduce the frequency of calls without compromising performance.
Function image stabilization
Debounce: When an event is continuously triggered and no event has been triggered for a certain period of time, the event handler is executed once. If the event is triggered again before the specified time, the delay is restarted.
function debounce(fn, delay) { var timer = null; return function() { if(timer ! == null) clearTimeout(timer); timer = setTimeout(fn, delay); Function handle() {console.log(math.random ()); } // eg: the scroll event window.addEventListener('scroll', debounce(handle, 1000));Copy the code
Function of the throttle
Function throttling: Ensures that event handlers are called only once in a certain period of time when events are continuously emitted. Throttling popular explanation is like our tap water, as soon as the valve is opened, the water pouring down, holding the good traditional virtue of thrift, we have to turn the tap down a little, it is best to be as we will according to a certain rule in a certain time interval drop by drop.
/** * Throttling Function * @param {Function} fn callback Function * @param {Number} delay Interval * @param {Boolean} immediate Whether the callback Function is executed immediately */ Function throttle(fn, delay, immediate = true) { if (immediate) { let nowTime; return function () { if (! nowTime || Date.now() - nowTime >= delay) { fn.apply(null, arguments) nowTime = Date.now(); } } } else { let timer; return function () { if (timer) return; timer = setTimeout(() => { fn.apply(null, arguments); timer = null; }, delay) } } }Copy the code