快速理解防抖与节流

本文介绍了JavaScript中的函数防抖(debounce)和函数节流(throttle)概念,并展示了如何在Vue项目中应用防抖技术优化输入框搜索功能。通过设置延迟执行回调,减少API请求频率,提高用户体验。
摘要由CSDN通过智能技术生成

 

函数防抖(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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值