函数防抖(debounce):
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。
使用vue实现防抖操作
<input type="text" class="input" v-model="searchText" @keyup="debounce"/>
var timer = undefined
debounce: function(){
let that = this
if(timer){
clearTimeout(timer)
}
timer = setTimeout(function () {
console.log('输入')
timer = undefined;
},2000)
}
函数节流(throttle):
规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。
使用vue实现节流操作
<button @click="throttle">点我</button>
var timer = undefined
throttle: function(){
let that = this
let now = +new Date();
if(lastTime && lastTime - now < 2000){
clearTimeout(timer)
}
timer = setTimeout(function () {
console.log('点击')
lastTime = +new Date()
},200)
}