防抖和节流
一、防抖
注:clearTimeout(timer)会保留一个计时器,此时的timer不是null,以timer为判断条件是true
建议
clearTimeout(timer);
timer=null;
同时使用
防抖分为两种
1.立即防抖:直接调用函数之后一定时间内连续触发事件不会调用函数,只执行第一次
2.非立即防抖:一定时间没有连续触发事件才调用函数,只执行最后一次
1.立即防抖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>立即防抖</title>
</head>
<body>
<button>立即防抖</button>
</body>
<script>
const content="点击就送999屠龙刀"
document.querySelector('button').onclick = debounce(log, 1000)
function log(content) {
console.log(content);
}
function debounce(fn, delay) {
let timer;
return function () {
if (!timer) {
fn.apply(this,[content]);
}
clearTimeout(timer)
timer=null;
timer = setTimeout(() => {
clearTimeout(timer)
timer = null;
}, delay)
}
}
</script>
</html>
2.非立即防抖
<body>
<button>非立即防抖</button>
</body>
<script>
const content="点击就送999屠龙刀"
document.querySelector('button').onclick = debounce(log, 1000)
function log() {
console.log(content);
}
function debounce(fn, delay) {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
timer=null;
}
timer = setTimeout(() => {
fn.apply(this,[content])
}, delay)
}
}
</script>
</html>
二、节流
节流:规定时间内只能执行一次调用函数
<body>
<button>节流</button>
</body>
<script>
const content="点击就送999屠龙刀"
document.querySelector('button').onclick = throttle(log, 1000)
function log(content) {
console.log(content);
}
function throttle(fn, delay) {
let timer;
return function () {
if (!timer) {
fn.apply(this,[content]);
timer=setTimeout(()=>{
clearTimeout(timer)
timer=null;
},delay)
}
}
}
</script>
</html>