What are function throttling and function stabilization? Solve what problem?
Function throttling and function stabilization are both solutions to optimize the performance of frequently called functions by delaying execution and reducing the number of calls.
The principle of
Use setTimeout to hold functions to be executed, and clearTimeout to clear functions to be executed when appropriate.
What’s the difference?
The trigger time of the two should include immediate execution and non-immediate execution. The non-immediate execution is used to distinguish the two from each other by the time when the same function is called for many times and triggered again
Throttling: No matter how many times the click is triggered, the function will be triggered again after the interval is over.
Anti-shake: the function will not be triggered again in the process of multiple clicks. The function will be triggered again when the click operation stops and the interval is exceeded.
Summary: For frequent calls over a period of time, anti-shake is to delay the execution of a later call, throttling is to delay the timing of multiple calls.
How to do?
Throttling:
let throttleSetTimeout = null let throttleCount = 0 let throttleSuccessTime = 0 document.getElementsByClassName('main')[0].onclick = function () { if (throttleSetTimeout) { throttleCount++ Console. log(' button clicked times ', throttleCount); Return} throttleSetTimeout = setTimeout(() => {throttleSuccessTime++ console.log(' number of successful requests: `, throttleSuccessTime) clearTimeout(throttleSetTimeout) throttleSetTimeout = null }, 1000) }Copy the code
Stabilization:
let debounceSetTimeout = null let debounceSuccessTime = 0 let debounceClickTime = 0 document.getElementsByClassName('main')[1].onclick = function () { if (debounceSetTimeout) { debounceClickTime++ Console. log(' button clicked times ', debounceClickTime); ClearTimeout (debounceSetTimeout)} // If the method fires more than once, clear the last recorded code with clearTimeout and restart the timer. DebounceSetTimeout = setTimeout(() => {debounceSuccessTime++ console.log(' number of successful requests: ',debounceSuccessTime) // If the event is not refired during the timing period, the object code will be executed after the delay time expires. }, 1000) // Delay the execution of code}Copy the code