防抖/节流

开发中需要运用的场景:
1、对提交按钮进行变态的点击压力测试
2、输入框内容的实时校验(譬如验证用户名是否已存在)
3、图片滚动加载scroll操作
4、窗口放大缩小resize操作
5、对某一区域进行mousemove操作

防抖(点击事件为例)

//事件的最后执行(在规定的时间t内,如果连续触发某一事件,则不会调用事件回调函数;连续触发某一事件,t时间内,不再触发该事件,则执行事件回调函数。)
//在公共方法中
 export const  debounce =   function(fn, delay) {
        var timer = null;
        return function() {
            timer && clearTimeout(timer);
            var context = this,         // 将执行环境指向当前dom
                arg = arguments;        // 事件e
            timer = setTimeout(function() {
                fn.call(context, arg);
            },delay);
        }
    }
 //在公共方法中引用防抖方法 
import debounce from '   '
<button @click="submit">提交</button>
<script>

    submit:debounce(()=>{
    //调用后台服务
    save(obj).then(()={}).ctach((){})
    }, 1000));
</script>

//事件的开始执行(点击事件后立即执行,在接下来的连续触发中,不执行事件回调函数)
 function debounce(fn, delay, isImmediate) {
        var timer = null;
        return function() {
            timer && clearTimeout(timer);
            var context = this,         // 将执行环境指向当前dom
                arg = arguments;        // 事件e

            if(isImmediate) {
                !timer && fn.call(context, arg);    // timer为null(即没有被执行过,或被重置)
                // 立即执行,后续连续点击不起作用
                timer = setTimeout(function() {
                    timer = null;
                }, delay);
                
            } else {
                timer = setTimeout(function() {
                    fn.call(context, arg);
                },delay);
            }
        }
    }

节流(touchmove事件为例)

function throttle(fn, delay) {
        var start = new Date();
        return function() {
            var context = this,         // 将执行环境指向当前dom
                arg = arguments;        // 事件e
            var current = new Date();

            if(current - start >= delay) {
                fn.call(context, arg);
                start = current;
            }
        }
    }

在页面中的使用(搜索按钮防抖)

onSearch:debounce(function() {
      let params = {
        username: this.searchValue,
        tenantId: this.userInfo.tenantId
      };
      pageSearch(
        Object.assign(
          {
            current: this.currentPage,
            size: this.pageSize,
          },
          params
        )
      ).then(response => {
        console.log('调服务');
        this.list = response.data.data.records;
        if (this.list.length == 0) {
          this.emptyShow = true;
        } else {
          this.emptyShow = false;
        }
        this.total = response.data.data.total;
      });
    },1000),
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值