The stabilization and the throttle JS

JS- image stabilization and throttle

  When making resize the window, scroll, verify the contents of the input box and other operations, if the frequency of the event handler function calls unlimited, will increase the burden on the browser, the user experience is very bad. At this point debounce (anti-shake) and throttle (throttling) the way we can use to reduce the frequency of calls, without affecting the actual results. 

Anti-shake function

  Function Image Stabilization (debounce): When the event to keep firing certain period of time no longer trigger event, the event handler will be executed once, if before the set time comes, once again triggered the event, on the re-start delay. When the following figure for triggering scroll event, does not perform the function handle, when there is no trigger event within 1000 milliseconds scroll, scroll will delay trigger event.

Together to achieve a simple debounce ~

Shake debounce Code:

1  // Stabilizer 
2  function Debounce (Fn, the wait) {    
 . 3      var timeout = null ;    
 . 4      return  function () {        
 . 5          IF (timeout ==! Null ) the clearTimeout (timeout);        
 . 6          timeout = the setTimeout (Fn, the wait);    
 7      }
 8  }
 9  // handler 
10  function handle () {    
 . 11      the console.log (Math.random ()); 
 12 is  }
 13 is  // scroll event 
14 window.addEventListener('scroll', debounce(handle, 1000));

When continuous scroll trigger event, the event handler will handle only one call at 1000 milliseconds after the stop scrolling, that is in the process of continuous triggering scroll event, the event handler handle has not been implemented.

Throttle function

  Function throttle (throttle): When the event to keep firing, to ensure that only a certain period of time to call an event handler. Throttling popular explanation for example, we turn on the water faucet, a valve is opened, water rushing down the stream, is holding fine traditional virtues of thrift, we want to tap off a small point, it is best as we follow certain rules in mind a drop by drop over a time interval of dripping. The following figure, when the continuous scroll trigger event, does not perform the function handle immediately, will be performed once every 1000 milliseconds handle functions.

The main function of the throttle there are two methods: a time stamp and a timer. Next are two ways to achieve throttle ~

Code throttle throttle (time stamp):

 1 var throttle = function(func, delay) {            
 2   var prev = Date.now();            
 3   return function() {                
 4     var context = this;                
 5     var args = arguments;                
 6     var now = Date.now();                
 7     if (now - prev >= delay) {                    
 8       func.apply(context, args);                    
 9       prev = Date.now();                
10     }            
11   }        
12 }        
13 function handle() {            
14   console.log(Math.random());        
15 }        
16 window.addEventListener('scroll', throttle(handle, 1000));

  When the high-frequency event is triggered, for the first time will be executed immediately (to scroll event binding function and the interval is generally greater than the real trigger event delay, if you have to load the page within 1000 milliseconds went scroll, I have no idea o (╥﹏╥) o), and then how frequently trigger events, they are also each delay time to execute once. When the trigger is completed after the last event, the event will no longer be carried out (the last time interval triggering event and penultimate event trigger is less than the delay, less than Why? Because it is greater than not called a high frequency (* ╹ ▽ ╹ *)).

Code throttle orifice (Timer):

1  // throttle throttle Code (Timer): 
2  var throttle = function (FUNC, Delay) {            
 . 3      var Timer = null ;            
 . 4      return  function () {                
 . 5          var context = the this ;               
 . 6          var args = arguments;                
 . 7          IF ( ! Timer) {                    
 . 8              Timer = the setTimeout ( function () {                        
 . 9                 func.apply(context, args);                        
10                 timer = null;                    
11             }, delay);                
12         }            
13     }        
14 }        
15 function handle() {            
16     console.log(Math.random());        
17 }        
18 window.addEventListener('scroll', throttle(handle, 1000));

  When the triggering event, we set a timer, when the triggering event again, if there is a timer, not executed until after the delay time, the timer function execution and emptied timer, so you can set the next timer device. When the first trigger event, the function will not be executed immediately, but only after execution delay seconds. And then how frequently a trigger event, are also each delay time to execute once. When the trigger after the last stop, because the timer delay delay may also perform a function.

  Throttle with a time stamp or a timer are possible. More precisely, it is possible, when the first trigger event immediately execute the event handler with a time stamp + timer, after the last trigger event will also execute an event handler.

Code throttle orifice (timestamp + Timer):

1  // throttle throttle Code (timestamp + Timer): 
2  var throttle = function (FUNC, Delay) {     
 . 3      var Timer = null ;     
 . 4      var the startTime = Date.now ();     
 . 5      return  function () {             
 . 6          var = curTime Date.now ();             
 . 7          var Remaining Delay = - (curTime - the startTime);             
 . 8          var context = the this ;             
 . 9          var args = arguments;             
 10         clearTimeout(timer);              
11         if (remaining <= 0) {                    
12             func.apply(context, args);                    
13             startTime = Date.now();              
14         } else {                    
15             timer = setTimeout(func, remaining);              
16         }      
17     }
18 }
19 function handle() {      
20     console.log(Math.random());
21 } 
22 window.addEventListener('scroll', throttle(handle, 1000));

  Use startTime start time inside the throttle function, the current time delay and to calculate the remaining curTime Remaining time, when the remaining <= 0 indicates that the executed when the event handler (to ensure that the first trigger event can be performed immediately and event handlers event handler executed once every delay time). If not, then it is time to set the trigger (to ensure that after the last trigger event can perform another event handler) in the time remaining before. Of course, in the remaining period of time if another triggering event, it will cancel the current timer, and a remaining recalculated to determine the current status.

to sum up

  Function Image Stabilization: several operations will be consolidated into one for this operation. The principle is to maintain a timer function is triggered after a specified delay time, but the trigger again within the delay time, the timer will reset before the cancellation. As a result, only the last operation can be triggered.

  Throttle function: making only trigger once within a certain time function. The principle is to determine whether a certain time to reach the trigger function.

  Differences: function throttle trigger no matter how often the event will ensure that you will perform a real event handler within the specified time, and anti-shake function only triggers a function only after the last event. For example, in a scene loaded infinite pages, we scroll the page when users need, from time to time send an Ajax request, rather than stopping when the user scrolls the page to request operational data. Such a scenario, it is suitable for expansion techniques.

Reference blog: https://www.cnblogs.com/momo798/p/9177767.html

Guess you like

Origin www.cnblogs.com/nayek/p/11788981.html