防抖:如果短时间内持续触发某个方法,只会执行一次
节流:如果短时间内持续触发某个方法,每隔一段时间执行一次。
他们的本质都是高阶函数。对要执行的函数进行包装。
<html>
<body>
<div id="app">
<button onclick="fn()">点击</button>
</div>
</body>
<script>
let fn = throttle(say, 1000)//debounce(say, 1000)
function say() {
console.log('说嘛')
}
function debounce(fn, wait) {
var timerId;
return function () {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(function () {
fn();
timerId = null
}, wait);
}
}
function throttle(fn, time) {
let run = true;
return function () {
if (!run) {
return
}
setTimeout(() => {
fn()
run = true
}, time)
run = false
}
}
</script>
</html>
网友评论