Debounce
- 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.
- For example: a commonly used scene, input box search, every time after the input of associative words, the control method of associative words can not be triggered as soon as the content of the input box changes, he must be triggered when you end the input for a period of time.
Function debounce(fn,delay){let timer = null return function() {if(timer){clearTimeout(timer)} The timer = setTimeout (fn, delay) / / simplified writing}} function showTop () {var scrollTop = document. The body. The scrollTop | | Document. The documentElement. ScrollTop; Console. log(' scrollbar position: '+ scrollTop); } window.onscroll = debounce(showTop,1000)Copy the code
Throttling (thorttle)
- High frequency events fire, but only execute once in n seconds, so throttling dilutes the frequency of the function’s execution
- Example: A scheduled function is executed only when the execution period is greater than or equal to. Just like when you buy a limited number of hot goods on Taobao, you constantly click refresh point to purchase, but there is always a period of time when you click on the effect, so you use throttling, is afraid of clicking too fast will cause bugs in the system
function throttle(fn,delay){ let valid = true return function() { if(! Valid){// Rest time no call return false} // Work time, execute the function and set the status bit to invalid during the interval valid = false setTimeout(() => {fn() valid = true; }, delay)}} /* Note that the throttling function is not implemented in the above way. For example, setTimeout can be completely dispensed with. You can replace the status bit with a timestamp, and then determine if the timestamp difference is greater than the specified interval. The return mark of setTimeout can also be directly taken as the judgment condition -- to determine whether the current timer exists. If it exists, it indicates that it is still cooling down, and eliminating the timer after fn execution means activation. Principle is the same * / function showTop () {var scrollTop = document. The body. The scrollTop | | document. The documentElement. The scrollTop; Console. log(' scrollbar position: '+ scrollTop); } window.onscroll = throttle(showTop,1000)Copy the code
The difference between
- Anti-jitter means to turn multiple executions into the last execution, and throttling means to turn multiple executions into intermittent execution.