Advanced JavaScript Series throttle [throttle] and stabilization [debounce]

First, the concept

These two things are in order to optimize the project occur, the official is not specifically defined, their presence is mainly to solve some of the events bring rapid succession of poor execution and huge memory consumption and other performance problems;
events such as these are generally like scroll keyup mousemove resize, etc., continue to trigger a short time, consumed in the performance is very large, especially some change operation DOM structure;

Throttle [throttle] and stabilization [debounce] are very similar, so that the above provisions in the event of such events trigger many times from time to constantly change reaches a predetermined trigger;

Throttling [Throttle]

Throttling popular explanation for instance, we turn on the water tap, a valve is opened, the water rushing down stream, this holds good traditional virtue of thrift, we need to tap off a small point, preferably in mind as we follow certain rules drop by drop over a time interval of dripping, it ,,, Well this is our concept throttling;
replace function, using the setTimeout method, given two times a later time by subtracting the previous time , we arrive at a given time in order to trigger this event once, so to speak too general, we look at the following function, here we [scroll], for example;

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

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

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

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

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

Through the above function, we can achieve the effect of throttle trigger once, of course, time can customize every 300 milliseconds specified, based on the demand;

Stabilizer [debounce]

Before writing code, let's understand what the concept of image stabilization, do not know if you have not done any advertising suspended on both sides of the computer side window of such a thing, when we drag the scroll bar when advertising on both sides of the window because drag the scroll bar dynamic, and constantly try to living in the middle, and then you will see two windows, kept shaking ah shake;

In general this is called jitter, and we need to do is to prevent this jitter, called image stabilization [debounce];

Here is the idea that when we shake drag is complete, the window position on both sides to re-calculate, so that will be very very smooth, looking very comfortable, and the number of major operations DOM structure is greatly reduced;

Optimize page performance, reduced memory consumption, or you like IE point this older version of the browser, maybe she jumped directly to you

That is, until an event is not over, the function will not execute a written statement that, when finished, we have given the delay time, then he go to perform this function after a given delay time, and this is proof 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 executed before the function, let's clear the timer, if the function has been executed, it will continue to clear the timer method, we know that after the end of the operation, the function will be performed;

In fact, I am writing problem with the way a lot, mainly ideas, we write more naturally know;

use

  1. When we do keyup like background check request, they can use the anti-shake function, otherwise we would request every time you press a keyboard, too frequent request, so that when we go to the end of the keyboard when the request with a lot less, and natural performance Needless to say;
  2. resize window resizing, we can use a throttle stabilization techniques may also be used;
  3. mousemove mouse motion events we can either adopt anti-shake can also use the throttle;
  4. Scroll bar scroll event trigger, of course, can be used both anti-shake can also be used throttle;
  5. Continuous high frequency of events can be made using these two methods to solve, optimize page performance;

Which specific use of more appropriate and more, mainly to see your business needs, well herein, this has to end here, thank you for reading;


Hand is not easy, not easy to summarize, please indicate the source, thank;

Guess you like

Origin www.cnblogs.com/homehtml/p/11795827.html