Image stabilization function
concept
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, which is generally used for input real-time query
Train of thought
Cancels the original delay event when a high frequency event is triggered
const debounce = (fn: any, delay = 1000) => { console.log('1') let timeout = null as any; return function() { console.log(timeout, '2') timeout && clearTimeout(timeout); timeout = setTimeout(fn, delay); }} const handlerChange = debounce(function () {alert(' update triggered ')}) // Bind listener document.querySelector("input").addEventListener('input', handlerChange);Copy the code
The throttle
concept
High frequency events are triggered, but only execute once in n seconds, so throttling will dilute the execution frequency of the function;
Train of thought
Each time the event is triggered, it will judge whether there is a delay function waiting to be executed. If there is, the event will be directly truncated without further execution
const throttle = (fn) => { let canUse = true; return () => { if (! SetTimeout (() => {canUse = true}, 500)}}Copy the code
Relevant reference
Zhihu: function anti – shake and function throttling guru Stuart zhengmei’s article.