Image stabilization and a small throttle case

  I referred to the practical application of anti-shake function in js with the throttle in the previous article, the direct and user experience as well as the browser loads, server load-dependent, it is necessary to shake the throttle for front-end developers One technique to master. Here's a little according to case embodied the role of anti-shake and throttling.

  First, no mouse movement and anti-shake event throttling process:

1 var num = 1;
2         var oWrap = document.getElementById('wrap');
3         function count (){
4             oWrap.innerHTML = num++;
5         }
6         oWrap.onmousemove = count;

  The above code, div bound to mouse move events when the mouse moves around inside the box, the event handler is called also continued, this will cause unnecessary load on the browser.

Anti-shake function (debounce)

  Anti-shake function (debounce): refers to the trigger event is executed after the specified time only once, if at a specified time and the event is triggered, then recalculate the function execution time, anti-shake function is divided into immediate execution and non-immediate execution Edition version

Non-executive version now:

 1 function debounce(fn,wait){
 2             var timeout;
 3             return function(){
 4                 var context = this;
 5                 var args = arguments;
 6                 if(timeout){
 7                     clearTimeout(timeout);
 8                 }
 9                 timeout = setTimeout(()=>{
10                     fn.apply(context,args)
11                 },wait);
12             }
13         }
14         oWrap.onmousemove = debounce(count,1000);

 

  

  When the non-implementation of anti-shake function results immediately displayed as the mouse moves around inside the box (gif here to see results, real moving), the function is not performed immediately, after 1000ms event function will be performed once, when I was in the trigger after the event trigger event execution time will be recalculated again within 1s and execute the function after the event

 

Guess you like

Origin www.cnblogs.com/zsp-1064239893/p/11606321.html