0%

每日一题

什么是防抖和节流?有什么区别?如何实现?

个人题解

防抖

在一个时间段内,如果有触发多次,只执行一次.

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
const debonce = (fn, timer) => {
let loop = null;
return function () {
if (loop) {
clearTimeout(loop);
}
loop = setTimeout(() => {
fn.apply(this, arguments);
}, timer);
};
};

function demo(arg1, arg2) {
console.log(arg1, arg2);
}

let debonceDemo = debonce(demo, 1000);
let i = 0;
let test = setInterval(() => {
console.log(i);
debonceDemo(1, 2);
if (++i > 100) {
clearInterval(test);
}
}, 10);

节流

不论执行速度有多快,固定时间内执行的次数只有一次

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
const throttle = (fn, timer) => {
let loop = true;
return function () {
if (!loop) {
return;
}
loop = false;
setTimeout(() => {
fn.apply(this, arguments);
loop = true;
}, timer);
};
};

function demo(arg1, arg2) {
console.log(arg1, arg2);
}

let throttleDemo = throttle(demo, 1000);
let i = 0;
let test = setInterval(() => {
console.log(i);
throttleDemo(1, 2);
if (++i > 100) {
clearInterval(test);
}
}, 100);

最高赞题解

防抖

触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间

思路:

每次触发事件时都取消之前的延时调用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function debounce(fn) {
let timeout = null; // 创建一个标记用来存放定时器的返回值
return function () {
clearTimeout(timeout); // 每当用户输入的时候把前一个 setTimeout clear 掉
timeout = setTimeout(() => { // 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
fn.apply(this, arguments);
}, 500);
};
}
function sayHi() {
console.log('防抖成功');
}

var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi)); // 防抖

节流

高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

思路:

每次触发事件时都判断当前是否有等待执行的延时函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function throttle(fn) {
let canRun = true; // 通过闭包保存一个标记
return function () {
if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
canRun = false; // 立即设置为false
setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中
fn.apply(this, arguments);
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
canRun = true;
}, 500);
};
}
function sayHi(e) {
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));

相关链接

第 3 题:什么是防抖和节流?有什么区别?如何实现?