学习js函数节流,优化性能

最近在做优化时,偶然看到了防抖和节流,让我们先简单的聊一下节流吧
节流 就是阻止一个函数在指定时间段内频繁的执行,是其在指定时间段内只能执行一次方法

  • 节流的原理很简单:如果你持续触发某个事件,特定的时间间隔内,只执行一次。

  • 如鼠标拖动事件,鼠标多次点击事件,当触发事件的时候,我们设置一个定时器,再触发事件的时候,如果定时器存在,就不执行

  • 直到定时器执行,然后执行函数,清空定时器,这样就可以设置下个定时器。
    不用节流的写法,尝试过就会发现事件在短时间内会不停触发,看到的效果也不好,数字改变的太快了

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #wrapper {
            width: 100%;
            height: 140px;

            background: skyblue;

            color: #fff;
            font-size: 30px;
            font-weight: bold;
            line-height: 140px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="wrapper"></div>

   
</body>
<script>
        var count = 1;
        function moveAction () {
             oWrapper.innerHTML = count++;              
        }

        var oWrapper = document.querySelector('#wrapper');
		oWrapper.onmousemove = moveAction;


    </script>

</html>

节流思想的写法 运用定时器,在规定事间内才执行真正的方法,改变一个数字大小,这样即使触发的太快,数字也是500毫秒才改变一个

 <script>
        var count = 1;
        let timer=null;
        let n=0;
        let set=0;
        //启动单个定时器,在延迟后调用指定的功能。该函数返回一个唯一的ID,该Id可以用于取消定时器    var id = setTimeout(fn, delay); 
        function moveAction () {
            n++;
            if(timer){  
            //这个timer每次执行完都会变成null,如果没执行,重复调用这个函``						数的话,直接return,好办法!!                
                console.log("n执行了"+n+'次')
                return;
            } //一般n这个语句执行了20多次,定时器回调才执行2次,
            timer=setTimeout(function(){ //timer什么时候有?timer是每个开					启的定时器的唯一标志
                set++;
                console.log("set执行了"+set+'次')
                console.log("stimer:"+timer)
                oWrapper.innerHTML = count++;
                timer=null;
            },500) 
        }

        var oWrapper = document.querySelector('#wrapper');
		oWrapper.onmousemove = moveAction;


    </script>

这个节流思想原来之前在练手vue时,也有应用,只是当时没发觉
要实现的时滑动右侧一列字母时,明细数据也随之切换,如滑动到H,明细里也跟着显示H开头的城市,不用定时器限制执行时间的话,会觉得明细切换太快了
在这里插入图片描述

<template>
    <!-- <div id="container_alpha" > -->
     
       <ul class="alphbet_list" ref="container_box"> 
        <li class="item" v-for="item of alphas" :key="item.id" @click="change_CityList($event)"
        @touchmove="handleTouchMove"   @touchend="handleTouchEnd"    @touchstart="handleTouchStart" :ref="item.alpha">
            {{item.alpha}}   
        </li>
        
    </ul>
    <!-- </div> -->
</template>
handleTouchStart(e){
            this.touch_start=true;
            // console.log('开始触摸');
            
        },
        handleTouchMove(e){
            let alpha_arr=[];
            for(let i in this.alpha_obj){
                alpha_arr.push(i);
            }
            if(this.timer){//函数截留
                //clearTimeout(this.timer);
                return;
            }
            let that=this;
            this.timer=setTimeout(function(){  //箭头函数中的this,限制拖动显示频率
                if(that.touch_start==true){
                // let y=this.$refs['A'][0].offsetTop;//offsettop是相对于父元素而言的
                    let top_a=that.$refs['A'][0].getBoundingClientRect().top,
                    top_b=that.$refs['B'][0].getBoundingClientRect().top;
                    let cur_y=e.touches[0].clientY
                    let dev=Math.floor((cur_y-top_a)/( top_b-top_a));
                    if(dev>=0&&dev<alpha_arr.length){
                        let letter=alpha_arr[dev];
                        that.$parent.handleLetterChange(letter);
                    }
                     that.timer=null;//执行了定时器就将timer置为null
                }
            },16)
            
            // console.log("触摸不松动");
        },
        handleTouchEnd(){
            this.touch_start=false;
            // console.log("刚结束触摸");
        }

有关引用 https://blog.csdn.net/jbj6568839z/article/details

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值