js防抖节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
防抖简陋用法
let timer = null;
function debounce(fn, delay = 300) {
clearTimeout(timer); // 重新计时
timer = setTimeout(fn, delay); // 一段时间后再执行回调
}
document.getElementById('keywords').oninput = () => {
debounce(ajax, 400); // ajax 异步请求搜索结果
}
防抖高级用法
function debounce(fn, delay = 300) {
return function(...args) {
clearTimeout(fn._timer_);
fn._timer_ = setTimeout(() => fn.apply(this, args), delay);
}
}

let ajax = e=>{console.log(e)}
document.getElementById('keywords').oninput = e => {
debounce(ajax, 400)(e.target.value); // ajax 异步请求搜索结果
}


节流简陋用法
let last = 0; // 记录上次执行的时间点
function throttle(fn, delay = 100) {
const now = Date.now(); // 本次时间点

// 本次与上次的执行时间间隔满足预设等待时间
if (now - last >= delay) {
last = now;
fn(); // 执行回调
}
}
节流高级用法
function throttle(fn, delay = 100) {
return function(...args) {
const now = Date.now();

clearTimeout(fn._timer_); // 总是清除上次延时回调

// 本次与上次的执行时间间隔不足预设等待时间
if (fn._last_ && now - fn._last_ < delay) {
// 让方法在脱离事件后也能执行一次
fn._timer_ = setTimeout(() => {
fn._last_ = now;
fn.apply(this, args);
}, delay);
} else { // 间隔时间满足条件,放行
fn._last_ = now;
fn.apply(this, args);
}
}
}

window.addEventListener('scroll', () => {
throttle(lazyLoad, 300)()
}, false);