JS防抖,节流,定时器清理

防抖:
概念:某一段时间内多次事件合并为一次执行,注意事件可多次触发但只执行一次

<input v-model="searchKey" placeholder="请输入关键字搜索文章"/>
// 在输入时一直触发watch事件就很烦,所以使用防抖可避免多次
watch: {
	searchKey (val) {
		if (!val) {
			if (this.timer) {
				clearInterval(this.timer)
			}
			this.articleList = []
			this.timer = null
			return
		}
		if (!this.timer) {
			this.timer = setTimeout(() => {
				this.$api.searchAritcle({title: val}).then(res => {
					if (res.success) {
						this.showEmpty = res.obj.length === 0
						this.articleList = res.obj
					}
				})
			}, 1000)
		} else {
			clearInterval(this.timer)
			this.timer = setTimeout(() => {
				this.$api.searchAritcle({title: val}).then(res => {
					if (res.success) {
						this.showEmpty = res.obj.length === 0
						this.articleList = res.obj
					}
				})
			}, 1000)
		}
	}
}

节流:
概念:一定周期时间内,事件只触发一次。比如滑动触底时要加载新数据,这里触底一次就加载就行。

// 思路一:一个时间段内只触发一次

·······省略触底事件条件··············
// seconds为2秒的时间戳大小,这里博主也不知道
const endTime = new Date().getTime
if (endTime - this.startTime > seconds) {
 	this.startTime = endTime   // 记录触发事件的时间戳初始值为0
 	console.log('执行触底事件的操作')
 }

// 一次触底事件完成之后,才能进行下一次

·······省略触底事件条件··············
if (this.doBottom) {
 	this.doBottom = false
 	console.log('执行触底事件的操作')
 	// 操作执行完之后
 	this.doBottom = true
 } else {
 	return
 }

定时器清理:
清理定时器时,单独的赋值为null是无效的且还是会执行,必须要使用clearInterval()
注意:clearInterval()清除了定时器之后this.timer会变成一个类型为Number的数字,所以!this.timer为false,这样验证码就只能获得一次,下次就不生效了。所以要设置为null

//  这里还没有调用接口获取验证码,就随便写了个
 takeCode () {
   if (!this.timer) {
     this.loginForm.code = '4396'
     this.hasCode = true
     this.timer = setInterval(() => {
       this.seconds--	// 初始为60
       if (this.seconds <= 0) {
         this.hasCode = false
         this.seconds = 60
         clearInterval(this.timer)
         this.timer = null
       }
     }, 1000)
   }
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值