函数防抖(debounce)
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
使用防抖函数完成输入框功能
<template>
<input @keyup="getData()" v-model="keyword" type="text"/>
<ul>
<li v-for="(item,index)in list" :key="index">{{list}}</li>
</ul>
</template>
<script>
export default({
data(){
return{
list:[],
timer:"",
keyword:""
}
},
methods:{
getData(){
if(this.keyword!=""){
clearTimeout(this.timer) //清楚定时器
var api = ""+this.keyword
this.timer=setTimeout(()=>{
this.$axios.get(api)
.then((res)=>{
this.list=res.data
}).catch((err)=>{
console.log(err)
})
},200)
}else{
this.list=[]
}
}
}
})
</script>
函数节流(throttle)
规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。
时间戳
let timer = null;
function throttle (fun,wait) {
return function () {
const argu = arguments;
// 事件触发,如果之前有等待的事件,则不作处理
if (timer) {
} else {
事件触发,前面没有事件在等待,则将事件进行等待执行
timer = setTimeout(function () {
fun();
}, wait);
}
}
}
// 调用
throttle(fun, 100)(argu1, argu2);