函数防抖(debounce) 当持续触发某事件时,一定时间间隔内没有再触发事件时,事件处理函数才会执行一次,如果设定的时间间隔到来之前,又一次触发了事件,就重新开始延时。 因为防抖的特性,一直执行最后一次的触发,所以可以用于鼠标移动确定最后一次移动的时候的坐标位置。
export const Debounce = (fn, t) => {
let delay = t || 500;
let timer;
return function () {
let args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
};
};
vue实例
<template>
<div>
<input type='text' v-model='value' @keydown = "hangleChange">
</div>
</template>
<script>
function debounce(func, wait=1000){ //可以放入项目中的公共方法中进行调用
let timeout;
return function(event){
clearTimeout(timeout)
timeout = setTimeout(()=>{
func.call(this, event)
},wait)
}
}
export default{
name:'',
data(){
return{
value:''
}
},
methods:{
hangleChange:debounce(function(e){
console.log(this.value)
})
}
}
</script>
函数节流(throttle) 当持续触发事件时,有规律的每隔一个时间间隔执行一次事件处理函数。 因为节流是监听到第一次触发事件后就执行,所以可以用来防止按钮多次点击执行多次,且按照第一次点击的事件为准
export const Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
};
};
vue实例
<template>
<div class="scroll" ref="previewText" @scroll.passive="fnScroll">
</template>
<script>
export default{
name:'globalHospot',
data(){
return{
count:0,
fnScroll:() =>{}
}
},
methods: {
fnHandleScroll (e) {
console.log('scroll触发了:' + this.count++, new Date())
},
fnThrottle(fn, delay, atleast){ //节流函数
let timer = null;
let previous = null;
return function(){
let now = +new Date()
if(!previous) previous = now;
if(atleast && now - previous > atleast){
fn();
previous = now;
clearTimeout(timer)
}else{
clearTimeout(timer)
timer = setTimeout(()=>{
fn();
previous = null
},delay)
}
}
}
},
created(){
this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //刚创建时执行
},
}
</script>