防抖
无论触发了多少次函数, 只执行最后一次函数(多次触发合并为一次)
<body>
<button id="btn">点我</button>
<script>
const btn = document.getElementById("btn")
btn.addEventListener("click", debounce(consoleClick, 500), false)
function consoleClick() {
console.log("点我" + Math.random() * 9)
}
function debounce(fn, delay) {
let timer = null
return function () {
let that = this,
args = arguments;
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}
</script>
</body>
节流:
不管你触发了多少次函数, 规定的时间内只执行一次(一定时间内的多次触发只取最后一次执行)
<!DOCTYPE HTML>
<html>
<body>
<button id="btn">点我</button>
</body>
<script type="text/javascript">
const btn = document.getElementById("btn")
btn.addEventListener("click", throttle(consoleClick, 800), false)
function consoleClick() {
console.log("点我" + Math.random() * 9)
}
function throttle(fn, wait) {
let timer;
return function () {
const context = this;
const arg = arguments;
if (!timer) {
timer = setTimeout(function () {
timer = null;
fn.apply(context, arg);
}, wait)
}
}
}
</script>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)