防抖和节流是什么?
防抖和节流是频繁触发事件的优化方案
防抖
避免频繁触发,最后一次触发事件后隔n秒后执行
应用场景
输入框搜索、文本框保存、表单提交按钮等等
手写防抖函数
有函数传参时的写法
/**
* @param {Function} fn
* @param {number} t milliseconds
* @return {Function}
*/
var debounce = function (fn, t) {
let timeId = null
return function (...args) {
if (timeId) clearTimeout(timeId)
timeId = setTimeout(() => fn(...args), t)
}
};
const log = debounce(console.log, 100)
log('Hello'); // cancelled
log('Hello'); // cancelled
log('Hello'); // Logged at t=100ms
无参写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<script>
const inputDOM = document.querySelector("input")
let counter = 1;
function searchChange() {
console.log(`第${counter++}次请求`);
}
inputDOM.oninput = debounce(searchChange, 500)
// 避免频繁触发,最后一次触发事件后隔n秒后执行
function debounce(fn, wait) {
let timer
return () => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn()
}, wait)
}
}
</script>
</body>
</html>
节流
减少触发事件,每隔n秒后执行
应用场景
scroll事件、拖拽事件、窗口大小调整
手写节流函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let counter = 1;
// 定义处理窗口大小调整的函数
function handleResize() {
console.log(`第${counter++}次请求`);
// console.log('窗口大小已调整:宽度 - ' + window.innerWidth + ', 高度 - ' + window.innerHeight);
}
// 添加事件监听器
window.addEventListener('resize', throttle(handleResize, 500));
function throttle(fn, wait) {
let timer
return () => {
if (timer) return
timer = setTimeout(() => {
timer = null
fn()
}, wait)
}
}
</script>
</body>
</html>