防抖节流

使用场景:

项目有个需求是输入框在输入的时候进行搜索,展示下拉数据,但是没必要输入一个字都进行搜索,所以想到了在输入结束200毫秒后再进行搜索,从而引出来了 js的节流(throttle),防抖(debounce)。

  • 函数概念
    函数防抖(debounce):
    在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。

    函数节流(throttle):
    规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只 有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。

防抖:防止抖动,单位时间内事件触发会被重置,避免事件被误伤触发多次。代码实现重在清零 clearTimeout
节流:控制流量,单位时间内事件只能触发一次,如果服务器端的限流即 Rate Limit。代码实现重在开锁关锁 timer=timeout; timer=null
区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行。

  • 实现代码
  1. 输入框,输入最后一个字 2秒后执行(防抖:debounce):
    例1
html:


js:
        debounce: function(){
            let that = this
      //定时器中的变量定义,会在每次执行函数的时候重复定义变量,产生严重的内存泄漏
            if(timer){  //timer在全局中定义
                clearTimeout(timer)
            }
            timer = setTimeout(function () {
                console.log('输入')
                timer = undefined;
            },2000)
        }

例2


tapToSearch(time) {
        var that = this
        that.listData = []
        var data = {
            session_secret: that.util.getStore('session_secret'), 
            page: that.page,
            pageSize:that.pageSize,
            content: that.searchContent, 
            status: that.statusLabel,
        } 
        delay(() => {
           var searchAssociationFlag = true
            if(searchAssociationFlag) { // 上一请求完后再发下一请求,防止频繁发送请求            
                searchAssociationFlag = false;
                that.listData = []
                api.pagelist(data, function (res) {
                    res.data.result.list.forEach(element => {
                    that.$set(element,'checked',false);
                    element.status = element.status==0 ? '已停售' : element.status==1 ? '销售中' :'已售罄' 
                    that.listData.push(element)
                    });
                    that.lastPage = res.data.result.lastPage
                    searchAssociationFlag = true;
                })
            }
        }, time);
        console.log(that.listData)
    },

2.在2秒内多次点击,只有一次生效(节流:throttle):

html:  
点我。。
js: throttle: function(){ let that = this let now = +new Date(); if(lastTime && lastTime - now < 2000){ //lastTime跟timer在全局定义 clearTimeout(timer) } timer = setTimeout(function () { console.log('点击') lastTime = +new Date() },200) }

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