# 防抖

函数防抖就是在函数需要频繁触发情况时,只有足够空闲的时间,才执行一次。 就好比🚌要等所有人上齐后才开

场景 实时搜素、拖拽

var inp = document.getElementById('inp');
var timer = null;
function request(e) {
    console.log(e, this.value);
}
inp.oninput = function () {
    var _self = this, _args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
    request.apply(_self,_args);
    }, 1000)
}
1
2
3
4
5
6
7
8
9
10
11
12

封装一下适用于多种情况

var inp = document.getElementById('inp');
function debounce(handler, delay) {
    var timer = null;
    return function () {
    var _self = this, _args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
        handler.apply(_self, _args);
    }, delay)
    }
}
function request(e) {
    console.log(e, this.value);
}
inp.oninput = debounce(request, 1000)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 节流

函数节流就是预定一个函数只有在大于等于执行周期的时候才执行,周期内调用不执行。 就好比💧积攒到一定重量才会落下来一样 场景 敞口调整、页面滚动、抢购疯狂点击

<div id="show">1</div>
<button id="btn">开始抢购</button>

var show = document.getElementById('show');
var btn = document.getElementById('btn')

function throttle(handler, wait) {
    var lastTime = 0;
    return function (e) {
    var nowTime = new Date().getTime();
    if (nowTime - lastTime > wait) {
        handler.apply(this, arguments);
        lastTime = nowTime;
    }
    }
}

function buy(e) {
    console.log(this, e);
    show.innerText = parseInt(show.innerText) + 1;
}
btn.onclick = throttle(buy, 1000)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22