防抖
防抖触发高频率事件时n秒后只会执行一次,如果n秒内再次触发,则会重新计算。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>debounce防抖</title>
</head>
<body>
<input type="text" id="search">
</body>
<script>
// 防抖
function debounce(func, delay) {
let timer = null;
return function (...args) {
// 清除原来定时器,重新设置新的定时器
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
function search() {
console.log("searching...");
}
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', debounce(search, 2000));
</script>
</html>
节流
高频事件触发,每次触发事件时设置一个延迟调用方法,并且取消之前的延时调用方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>throttle节流</title>
</head>
<body>
<div style="height:3000px"></div>
</body>
<script>
// 节流
function throttle(func, delay) {
let timer = null;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
// 使用节流优化滚动事件
window.addEventListener('scroll', throttle(function () {
console.log('scrolling...');
}, 1000));
</script>
</html>```