防抖函數(shù)(debounce):當一個函數(shù)連續(xù)觸發(fā)铐伴,只執(zhí)行最后一次。n秒內(nèi)觸發(fā)事件俏讹,函數(shù)只會執(zhí)行一次当宴,如果n秒內(nèi)再次觸發(fā),則會重新計算再次執(zhí)行函數(shù)的時間泽疆。
比喻:坐公交户矢,司機需要等最后一個人進入才能關(guān)門。每次進入一個人殉疼,司機就會多等待幾秒再關(guān)門梯浪。
節(jié)流函數(shù)(throttle):限制函數(shù)在一定時間內(nèi)只執(zhí)行一次。
比喻:乘坐地鐵瓢娜,過閘機時挂洛,每個人進入后3秒后門關(guān)閉,等待下一個人進入眠砾。
代碼實現(xiàn)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>防抖函數(shù)虏劲、節(jié)流函數(shù)</title>
<style>
.btn,
.btn2,
.btn3 {
width: 100px;
height: 100px;
background-color: red;
margin-bottom: 50px;
}
</style>
</head>
<body>
<div class="btn">點擊測試</div>
<div class="btn2">節(jié)流點擊</div>
<div class="btn3">防抖點擊</div>
<script>
const btn = document.querySelector('.btn');
const btn2 = document.querySelector('.btn2');
const btn3 = document.querySelector('.btn3');
let func = (name, age) => {
console.log('按鈕重復(fù)點擊了', name, age);
};
btn.onclick = func;
// 節(jié)流函數(shù)
const throttle = (fn, wait = 300, ctx) => {
let lastCall = 0;
return (...args) => {
const _args = args;
return () => {
const now = Date.now();
if (now >= lastCall + wait) {
lastCall = now;
fn.apply(ctx, _args);
}
};
};
};
const afterThrottle = throttle(func, 2000);
btn2.onclick = afterThrottle('小黑不黑', '18');
// 防抖函數(shù)
const debounce = (fn, wait = 300, ctx) => {
let lastCall = 0;
return (...args) => {
const _args = args;
return () => {
const now = Date.now();
if (now >= lastCall + wait) {
fn.apply(ctx, _args);
}
lastCall = now;
};
};
};
const afterDebounce = debounce(func, 2000);
btn3.onclick = afterDebounce('小白', '100');
</script>
</body>
</html>