做了一个小例子,深入的了解函数节流与防抖的区别
<!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>Document</title>
</head>
<body>
<input type="text" id="inp">
</body>
<script>
// 利用函数防抖 搜索功能,在0.5秒内只执行最后一次,如果在规定的时间内又触发了事件定时器则会重新计算
function debounce(fn) {
var timer = null;
return function () {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this)
}, 500)
}
}
function say() {
console.log("成功了")
}
document.querySelector("#inp").addEventListener("keydown", debounce(say))
// 监听改变窗口大小,在规定的时间内只计算一次
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));
</script>
</html>