The difference between js anti-shake and throttling and the use of debounce function (debounce) function throttling (throttle)

purpose

The following scenarios are often triggered by events frequently, so heavy behaviors such as DOM operations and resource loading are frequently performed, resulting in UI pauses and even browser crashes.

  • windowObject resize, scrollevent
  • mousemoveEvent when dragging
  • Shooting game mousedown, keydownevent
  • Text input, automatic completion keyupevents

In fact, for window resizeevents, the actual demand is mostly to stop the nsubsequent processing after changing the size for milliseconds; while most other events require subsequent processing to be performed at a certain frequency. In response to these two requirements, two solutions, debounce and throttle, have emerged.

Throttle (also known as throttling) and debounce (also known as debounce) are actually function call frequency controllers.

debounce

When you call the function nafter the second, before the action is performed, if at this ntime and re-calculate the execution time and within seconds before calling the function will be canceled, cite a simple example, we do want to suggest based on user input, every time the user presses You can cancel the previous time when you press the keyboard, and you only care about the time of the last input.

throttle

Throttle restricts the calling frequency 1sof a function within a certain threshold, for example , a function cannot be called twice.

The following is a practical demonstration

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">点击</button>
</body>
<script>
// 防抖 
function fangdou(fn,d){
    var delay = d || 600
    var timer ;
    return function(){
        var _this =this ;
        var arg =arguments;
        if(timer){
            clearTimeout(timer)
        }
        timer =setTimeout(function(){
            timer =null;
            fn.apply(_this,arg)
        },delay)
    }
}
function jieliu(fn,d){
    var delay = d || 600
    var timer;
    var last;
    return function(){
        var _this =this ;
        var arg =arguments;
        var now = +new Date();
        if(last && now-last <delay){
            clearTimeout(timer);
            timer = setTimeout(function() {
                        last = now;
                        fn.apply(_this, arg);
                    }, delay);
        }else{
            last = now
            fn.apply(_this, arg);
        }
}
}
// 时间戳
    // btn.onclick=function(){
    //     console.log(111)
    // }
    // btn.onclick=fangdou(function(){
    //     console.log(111,this)
    // },500)

       btn.onclick=jieliu(function(){
        console.log(111,this)
    },1000)
</script>

</html>

 

Guess you like

Origin blog.csdn.net/weixin_44360943/article/details/108632298