当我们需要阻止操作频繁触发时,或者不让接口频繁调取时,比如一个搜索输入框实时触发请求,onmousemove,onscroll等,就需要用到函数防抖与节流。
下面举例看:
<div id="number" class="num">0</div>
<script type="text/javascript">
var counter = 1
var content = document.getElementById('number')
content.onmousemove = debounce(count, 1000)
function count() {
content.innerHTML = counter++
}
// 函数防抖
function debounce(fun, wait) {
let timer
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(fun, wait)
}
}
</script>
函数防抖,短时间内多次触发同一事件,只执行最后一次,中间的不执行。
下面是函数节流:
// 函数节流
content.onmousemove = throttle(count, 3000)
function throttle(fun, wait) {
var timer = 0
return function () {
var now = new Date().getTime()
console.log(now)
if (now - timer > wait) { // 对比时间差,如果大于时间差就可执行
fun()
timer = now // 再把上次时间替换为本次时间
}
}
}
函数节流,指连续触发事件但是在 n 秒中只执行一次函数。节流如字面意思,会稀释函数的执行频率。