日常工作中,防抖与节流思想经常会使用到,特别防抖思想比较多,比如点击一个弹框确定按钮,防止多次点击发送请求。在扫码框扫码时,扫码枪性能原因可能短暂时间内会多次扫码等等。归纳整理2种防抖类型和节流通用函数
情况一:防抖,立马触发fn函数,频繁触发最后一次触发距离下次触发至少隔delay毫秒
函数如下:
let lastClickTime = 0;
function handleClick(callback, delag) {
const currentTime = Date.now();
if (currentTime - lastClickTime >= delag) { // 300毫秒的延迟,你可以根据需要调整
callback()
}
lastClickTime = currentTime;
}
使用测试:
<!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, maximum-scale=1.2">
<title>Document</title>
</head>
<body>
<button class="btn">按钮</button>
<script>
let btn = document.querySelector('.btn')
btn.addEventListener('click', () => {
let Fn = () => {
console.log('打印')
}
handleClick(Fn, 2000)
})
//防抖,立马触发fn函数,频繁触发的话,最后一次触发距离下一次触发超过delag时间才触发
let lastClickTime = 0;
function handleClick(callback, delag) {
const currentTime = Date.now();
if (currentTime - lastClickTime >= delag) { // 300毫秒的延迟,你可以根据需要调整
callback()
}
lastClickTime = currentTime;
}
</script>
</body>
</html>
情况二:防抖,开始不生效,频繁触发最后一次生效,最后一次触发距离下次触发至少隔delay毫秒
函数如下:
let timeoutId;
function debounceLast(callback, delay) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback()
}, delay);
}
使用测试:
<!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>Document</title>
</head>
<body>
<button class="btn">按钮</button>
<script>
let btn = document.querySelector('.btn')
btn.addEventListener('click', () => {
let Fn = () => {
console.log('打印')
}
debounceLast(Fn, 1000)
})
//防抖,开始不生效,频繁触发最后一次生效,最后一次触发距离下次触发至少隔delay毫秒
let timeoutId;
function debounceLast(callback, delay) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback()
}, delay);
}
</script>
</body>
</html>
情况三:节流,频繁点击时,每隔wait毫秒触发一次callback函数
函数如下:
let timerOut=null
function thro(callback, wait) {
if (!timerOut) {
timerOut = setTimeout(function () {
callback();
timerOut = null;
}, wait)
}
}
使用测试:
<!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, maximum-scale=1.2">
<title>Document</title>
</head>
<body>
<button class="btn">按钮</button>
<script>
let btn = document.querySelector('.btn')
btn.addEventListener('click', () => {
let Fn = () => {
console.log('打印')
}
thro(Fn, 5000)
})
//节流,频繁点击时,每隔wait毫秒触发一次callback函数
let timerOut=null
function thro(callback, wait) {
if (!timerOut) {
timerOut = setTimeout(function () {
callback();
timerOut = null;
}, wait)
}
}
</script>
</body>
</html>