防抖和节流

你是否在日常开发中遇到一个问题,实现一个按钮的防二次点击操作,否则用户频繁点击很有可能导致页面卡顿。

防抖动和节流本质是不一样的。防抖动是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行

防抖

任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行。

data(){
timer: null   //创建一个标记用来存放定时器的返回值
}
// 封装定时器清除函数
clearTimer() {
     if(this.timer) clearTimeout(this.timer) 
}
goToNext(){
    this.clearTimer() //如果已经设定过定时器了就把前一个定时器清除
    //然后创建一个新的 setTimeout
    this.timer = setTimeout(() => {
        this.qaIndex = this.qaIndex + 1 
        this.currentBtn = ''
        this.progress()
        }, 500)
}

结合上面的代码,我们可以了解到,在触发点击事件后,如果用户再次点击了,我们会清空之前的定时器,重新生成一个定时器。意思就是:这件事儿需要等待,如果你反复催促,我就重新计时!

节流

用户点击提交按钮,假设我们知道接口大致的返回时间的情况下,我们使用节流,这里只允许用户点击一次

data(){
  ageNum: '',
  phoneNum: '',
  btnDisable: false
}
submitFace(){
          if(!this.ageNum){
                    wepy.showToast({
                    title: '请填写您的年龄',
                    icon: 'none',
                    duration: 2000
                })
            }
            if(!this.phoneNum){
                    wepy.showToast({
                    title: '请填写微信/手机号',
                    icon: 'none',
                    duration: 2000
                })
            }
            if(this.ageNum && this.phoneNum){
                if(this.btnDisable) return // 2. 在函数开头判断标志是否为 true,为true 则中断函数
                wepy.showLoading({
                    title: '提交中...',
                    mask: true
                })
                this.btnDisable = true  // 1. 防止多次提交不断发请求
                this.$emit('btnDisable',this.btnDisable)
                wepy.request({
                  url: '/mobile/mina/face/save',
                  method: 'POST',
                  data: {
                      age: this.ageNum,
                      phone: this.phoneNum,
                      problemTypeList: this.saveTagList
                  }
                  }).then((res) => {
                    wepy.hideLoading()
                    if (res.resCode != 0) return
                    wepy.showToast({
                        title: '信息提交成功',
                        icon: 'success',
                        duration: 2000
                    })
                    this.btnDisable = false  // 3. 交成功后重置为false 变为可点状态
                  }
            }
}

你可能感兴趣的:(防抖和节流)