Home  >  Article  >  Web Front-end  >  Detailed explanation of throttling and anti-shake debounce of javascript function

Detailed explanation of throttling and anti-shake debounce of javascript function

小云云
小云云Original
2018-01-18 16:33:321939browse

This article mainly introduces the throttling [throttle] and anti-shake [debounce] of JavaScript functions. It introduces the principles and examples of throttling and anti-shake in detail. It has certain reference value. Those who are interested can learn more. I hope Can help everyone.

Anti-shake and throttling

When resize, scroll, input box content verification and other operations of the window, if these operation processing functions are more complex or the page When operations such as frequent re-rendering are performed, if the frequency of event triggering is unlimited, it will increase the burden on the browser and lead to a very poor user experience. At this time, we can use debounce (anti-shake) and throttle (throttle) to reduce the frequency of triggering without affecting the actual effect.

These two things appear for project optimization. There is no official definition. Their appearance is mainly to solve the poor performance and memory caused by some events that are continuously executed in a short period of time. Problems such as huge consumption;

Such events, such as scroll keyup, mousemove resize, etc., are triggered continuously in a short period of time, which consumes a lot of money in terms of performance, especially operations that change the DOM structure;

Throttle [throttle] is very similar to anti-shake [debounce]. They both allow the above-mentioned events to be triggered how many times within a specified period of time when the specified event changes from constant triggering to a specified time;

Throttle [throttle]

The popular explanation of throttling is like when we put water into the faucet, when the valve is opened, the water flows down. This upholds the fine traditional virtues of diligence and thrift. , we need to turn down the faucet, it is best to let it drip down drop by drop within a certain time interval according to a certain rule according to our will. This,,, well this is our concept of throttling;

In terms of a function, use the setTimeout method, given two times, subtract the previous time from the later time, and trigger the event once when the time we give is reached. This is too general. Let's look at the following function , here we take [scroll] as an example;


/** 样式我就顺便写了 **/
<style>
 *{padding:0;margin:0;}
 .scroll-box{
  width : 100%;
  height : 500px;
  background:blue;
  overflow : auto;
 } 
 .scroll-item{
  height:1000px;
  width:100%;
 }
</style>

------------------------


/** 先给定DOM结构;**/
<p class="scroll-box">
 <p class="scroll-item"></p>
</p>

---------------------


/**主要看js,为了简单我用JQ去写了**/
<script>
 $(document).ready(function(){
  var scrollBox = $(&#39;.scroll-box&#39;);
  //调用throttle函数,传入相应的方法和规定的时间;
  var thro = throttle(throFun,300);
  //触发事件;
  scrollBox.on(&#39;scroll&#39; , function(){
   //调用执行函数;
   thro();
  })

  // 封装函数; 
  function throttle(method,time){
   var timer = null;
   var startTime = new Date();
   return function(){
    var context = this;
    var endTime = new Date();
    var resTime = endTime - startTime;
    //判断大于等于我们给的时间采取执行函数;
    if(resTime >= time){
     method.call(context);
     //执行完函数之后重置初始时间,等于最后一次触发的时间
     startTime = endTime;
    }
   }
  }
  function throFun(){
   console.log(&#39;success&#39;);
  }
 })
</script>

Through the above function, we can achieve the throttling effect and trigger it every 300 milliseconds. Of course, the time can be customized according to needs;

Prevention Debounce [debounce]

Before writing the code, let’s first clarify the concept of anti-shake. I wonder if you have ever done something like floating advertising windows on both sides of the computer. When we drag the scroll bar Sometimes, the advertising windows on both sides will constantly try to be in the middle due to the dragging of the scroll bars, and then you will see these two windows shaking and shaking;

Generally this This is called jitter. What we have to do is to prevent this kind of jitter, which is called debounce;

The idea of ​​debounce here is that after we finish dragging, the positions of the windows on both sides will be reset. Calculation, in this way, will appear very smooth and comfortable to look at, and the number of times of operating the DOM structure, the most important thing, will be greatly reduced;

optimizes page performance and reduces memory consumption, otherwise you will be like IE If you use an older version of the browser, it might just pop up for you

In written terms, the function will not be executed until a certain event ends. When it ends, we give Delay time, then he will execute this function after the given delay time. This is the anti-shake function;

Look at the code:


//将上面的throttle函数替换为debounce函数;
function debounce(method,time){
 var timer = null ;
 return function(){
  var context = this;
  //在函数执行的时候先清除timer定时器;
  clearTimeout(timer);
  timer = setTimeout(function(){
   method.call(context);
  },time);
 }
}

The idea is that before the function is executed, we clear the timer first. If the function keeps executing, it will continue to clear the methods in the timer. The function will not be executed until our operation is completed;

In fact There are many ways to write, and it is mainly a question of ideas. The more you write, the more you will naturally understand; When we press the keyboard, we can use the anti-shake function. Otherwise, we will request it every time we press the keyboard. The request is too frequent. In this way, we will request again when we finish pressing the keyboard. The request will be much less, and the performance will naturally go without saying;

    resize When adjusting the window size, we can use anti-shake technology or throttling;
  1. mousemove mouse movement event, we can use either anti-shake technology or throttling Use throttling;
  2. Scroll events triggered by the scroll bar can of course use either anti-shake or throttling;
  3. Continuous high-frequency events Events can be resolved in these two ways to optimize page performance;
  4. Related recommendations:
  5. Detailed explanation of JS function throttling and anti-shake examples


Detailed explanation of throttling and anti-shaking of javascript functions

The meaning of function throttling and anti-shaking

The above is the detailed content of Detailed explanation of throttling and anti-shake debounce of javascript function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn