Debounce and Throttle
Debounce: A period of time after a function is triggered before it is executed. If the function is triggered repeatedly, the timer is reset and the function is executed only once
Case 1: the search box, if trigger request when I was in the input function to obtain prompt content, the browser will constantly sending requests when input, but the use of image stabilization, can pause when to enter and pause at a certain time to perform function (a pause indicates the user really need prompt, pause to a certain amount of time and then send the request to obtain prompt, If the user types quickly, the prompt is not needed, and the browser does not need to send a request to get the prompt.)
Case 2: The onresize event of the browser, if the function is frequently executed during the adjustment of the browser size, if the function is dom operation, the high frequency of DOM operation will affect the page display and browser performance, use anti-shake, the function is executed after the browser stops adjusting a period of time. Reduce unnecessary DOM manipulation (the throttling example in the Little Red Book is this one, but I think throttling and anti-shock are not clearly separated, and anti-shock is also throttling)
Implementation 1: The Little Red Book throttling example
Use timer, trigger to delete a timer, create a timer again, re-timing
/*fun is the function to be executed, delay is the interval, context is the execution context, */ function debounce(fn,delay,context){clearTimeout(fn.id) Fn. id=setTimeout(fn.bind(context),delay)} window.onresize = function(){debounce(fun,500)}Copy the code
Implementation 2: The use of closures, custom implementation of LoDash, cancellation and immediate execution functions.
E.adddeventlistener ('input',debounce(fun,1000,true)) function debounce = function(fn,delay){var Timer =null// timer // To be run function var debmentioning = function(){var _that = this// Save the context for calling the function var _arguments = arguments// Save the incoming parameters If (timer){clearTimeout(timer)} timer=setTimeout(function(){fn.apply(_that,_arguments)},delay)} // Cancel execution Debmentioning. Cancel = function(){if(timer){clearTimeout(timer) timer=null}} // Return debmentioning function}Copy the code
Whether the optimization is executed immediately, that is, when the function is fired repeatedly, it is executed the first time
For example, when typing quickly in the search box, a prompt will be executed immediately. If there is a pause and the pause lasts for a certain period of time, the function will be executed again to get the prompt. When the event is triggered again, the prompt will be executed immediately, and then again when the pause occurs
The function debounce (fn, delay, leading) {var timer = null/var/timer leading = leading | | false / / if the immediate execution var debounced = for the first time If (timer){clearTimeout(timer)} function(){var _that = this; var _arguments = arguments; If (leading){var isInvoke=false Timer){fn.apply(_that,_arguments) isInvoke=true} /* Update timer. */ timer=setTimeout(function(){timer=null /* If the event is triggered only once, it is already executed immediately, so do not execute the function */ if(! isInvoke){ fn.apply(_that,_arguments) } },delay) } else{ timer=setTimeout(function(){ fn.apply(_that,_arguments) },delay)}} // Cancel debmentioning. Cancel = function(){if(timer){clearTimeout(timer) timer=null}} return debmentioning}Copy the code
Throttling (throttle) : repeat call a function in a period of time, but the function will only perform a difference image stabilization, image stabilization is generally not executed immediately after trigger function, but a period of time will no longer trigger function to perform, and throttle is executed immediately when they call a function, but if the last time and perform the function of time interval does not meet the requirements, not executed.
Case 1: Click the button in the small game when the plane fires a bullet, click the button repeatedly, the plane only fires a bullet within a certain period of time
Implementation 1: Use timer and a switch
Function throttle(fn,interval){var timer=null,flag=true Function throttled(){var _this=this, _arguments=arguments if(flag){ Fn. apply(_this,_arguments) setTimeout(()=>{flag=true},interval)}} return throttled}Copy the code
Optimize whether to perform last time
Use a timer to control, when the flag is false, is to create a timer, within a specified time interval after the executive function, so even if not to the time interval will perform the final function, if within the timer function, flag to true and trigger the function, while the timer, only performs a function of the current event
Function throttle (fn, interval, option) {var timer = null, flag = true, option = option | | false / / the default last trigger function does not perform the function Throttled (){var _this=this, _arguments=arguments if(flag){if(timer){clearTimeout(timer) Apply (_this,_arguments) setTimeout(()=>{flag=true},interval)} // Set the last time else if(! timer&&option){ timer=setTimeout(()=>{ flag=false fn.apply(_fn,_arugments) timer=null setTimeout(()=>{ flag=true },interval) },interval) } } throttled.cancel=function(){ if(timer){ clearTimeout(timer) timer=null } } return throttled }Copy the code
Implementation 2: Use timestamps
Var throttled = function(){var _this = this var _arguments = function(fn,interval){var pre = 0 var throttled = function(){var _this = this var _arguments = arguments var now = new Date().getTime() if(now-pre>=interval){ fn.apply(_this,_arguments) pre=now } } return throttled }Copy the code
Optimizes whether to perform the last execution
The timer is implemented. If the last execution is required, the timer is created when the event is triggered for the first time. If the time between the last triggering event and the last function execution does not meet the requirements, the function will not be executed and the callback function in the timer will be executed finally
Var throttle = function (fn, interval, option) {var pre = 0, the timer = null, / / timer option = option | | false / / not perform final var throttled by default Function (){var _this = this var _arguments = arguments var now = new Date().gettime () if(now-pre>=interval){// Clear timer If (timer){clearTimeout(timer) timer=null} fn. Apply (_this,_arguments) pre=now} Create a timer to ensure that the function is executed again when the interval between the last trigger event and the last function execution is <interval. */ else if(! timer&&option){ timer=setTimeout(function(){ timer=null fn.apply(_this,_arguments) pre=now },interval) } } throttled.cancel=function(){ if(timer){ clearTimeout(timer) timer=null } } return throttled }Copy the code
Above code I have a simple test, the first time to write an article in the community, if there is a question or error welcome to point out ah ~ my code is mainly from the reference article, the article is written more clearly, and there are optimization return value, but I haven’t had time to digest, next time to supplement.
Reference: CodeWhy’s article “javascript Anti-Jitters and Throttling”