防抖和节流

首先要理解防抖函数的定义:当函数被连续调用时,并不执行设定的动作,只有当停止调用函数一段时间后才执行一次设定的动作.就像上电梯的时候,大家在上电梯的过程中门一直处于开的状态,只有当没有人上电梯一段时间后,电梯才会关门。

本例使用滚动事件为例

var $card = document.getElementById('card')
function scrollHandle(e) {
    console.log(e)    // 
    console.log(this) // 
}
$card.addEventListener('scroll', throttle(scrollHandle,1000))
// 先触发动作
function debounce1(func, wait) {
    var timeout; // 标记
    return function() {
        var that = this;
        var arg = arguments;
        timeout&&clearTimeout(timeout);
        !timeout && func.apply(that,arg)
        timeout = setTimeout(function(){timeout = null}, wait) 
    }
}
// 后触发动作
function debounce2(func, wait) {
    var timeout; // 标记
    return function() {
        var that = this;
        var arg = arguments;
        timeout&&clearTimeout(timeout);
        timeout = setTimeout(function(){func.apply(that,arg)}, wait) 
    }
}

节流就是节约流量,将连续触发的事件稀释成预设的频率.无论这期间触发多少次事件,都是按照预设的频率执行

// 先触发动作
function throttle1(func, wait) {
    var timeout;
    return function() {
        var that = this;
        var arg = arguments;
        if(!timeout){
            func.apply(that,arg);
            timeout = setTimeout(function() {
                clearTimeout(timeout);
                timeout = null;
            }, wait)
        } 
    }
}

// 后触发动作
function throttle2(func, wait) {
    var timeout;
    return function() {
        var that = this;
        var arg = arguments;
        !timeout&&(timeout = setTimeout(function() {
            clearTimeout(timeout);
            timeout = null;
            func.apply(that,arg);
        }, wait))
    }
}

 

posted @ 2020-04-02 12:34  Nicederen  阅读(148)  评论(0编辑  收藏  举报