记录一下防抖和节流的区别
防抖(debounce)
示例环境:点击事件。倒计时n秒,只认最后点击的那一次。每一次点击都会重新计时,直到最后一次点击。从最后一次点击开始倒计时n秒,再触发事件。
防抖(throttle)
示例环境:点击事件。倒计时n秒,在n秒内不管点击多少次,只会间隔n秒触发一次事件。
<template>
<div>
<button @click="printDebounce">防抖</button>
<button @click="printThrottle">节流</button>
</div>
</template>
<script>
// 封装一个防抖的函数 (我这里封装再组件内,也可以封装成专门的js文件)
function debounce(fn,delay){
// 先设置一个定时器
let timer = null
return function() {
// 如果这个时间内有多次触发,就清除定时器
let args = arguments
if(timer) {
clearTimeout(timer)
}
// 重置定时器 延迟时间
timer = setTimeout( ()=> {
timer = null
fn.apply(this,args)
},delay)
}
}
//封装一个节流的函数
function throttle(fn,delay){
// 记录上次一事件的调用时间
let last = 0
return function(){
let args = arguments
// 记录当前时间
let now = +new Date()
if((now - last) > delay){
// 如果当前时间- 上次调用的时间 大于 传入的时间。当前点击与上次点击的时间差 大于我们规定的时间 差,就可以触发点击事件
last = now
fn.apply(context,args)
}
}
}
export default {
data(){
return{
}
},
methods:{
// 通过点击事件调用防抖的方法。
printDebounce:debounce(function(e){
console.log('触发防抖')
},2000),
// 通过点击事件调用节流的方法。
printThrottle:throttle(function(e){
console.log('触发节流')
},2000)
}
}
</script>
不管点击多少次,只会最后一次点击倒计时2s后触发