美文网首页
JS - 函数节流和函数防抖

JS - 函数节流和函数防抖

作者: 饮杯梦回酒 | 来源:发表于2019-01-13 17:28 被阅读0次

    导读:

    • 函数节流和函数防抖是我们解决频繁触发DOM事件的两种常用解决方案,都对提升页面性能有显著的功效。

    例子:

    • 函数防抖:( 函数调用n秒后才会执行,如果函数在n秒内再被调用的话则上次调用的函数不执行且重新计算执行时间 )

    比如页面上注册邮箱时的邮箱输入框,其本身通过正则设置格式,而浏览器会随着用户的输入频繁检查格式,这将会对浏览器性能有很大消耗,于是设置n秒当用户两次输入之间的时间间隔大于n秒时,再执行检查。

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script type="text/javascript" src="../jquery-3.3.1.min.js"></script>
    </head>
    <body>
        <input type="text" id="email">
        <button>获取</button>
        <script type="text/javascript">
            const filter = /^([\w\_\.\-])+\@(([\w\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            $('#email').on('keyup', check());
            function check() {
                let timer = null;
                return function() {
                    let correct = filter.test($('#email').val());
                    timer = setTimeout(function() {         
                        if(correct) {
                            console.log('格式正确');
                        } 
                    }, 800)
                }
            }
        </script>
    </body>
    </html>
    
    • 函数节流:( 函数预先设定一个执行周期,当完成当前周期后,进入下一个新周期 )

    比如移动端的右侧地区首字母滚栏,通过手指滑动会频繁触发,这是极其消耗浏览器性能的,因此设置n秒为一个周期,只有当前周期执行完才能触发下一个周期。

    //  注意看 methods 中方法就行了我这里就不再分出来举例了
    <template>
        <ul class="list">
            <li class="item" v-for="item of letters" :key="item" @click="searchCity" @touchstart="touchStart" @touchmove="touchMove" @touceEnd="touchEnd" :ref="item">{{item}}</li>
        </ul>
    </template>
    
    <script type="text/javascript">
        export default {
            name: 'cityAlphabet',
            props: {
                cities: Object
            },
            computed: {
                letters() {
                    const letters = []
                    for(let i in this.cities) {
                        letters.push(i)
                    }
                    return letters
                }
            },
            data() {
                return {
                    touchStatus: false,
                    startY: 0,
                    timer: null
                }
            },
            updated() {
                this.startY = this.$refs['A'][0].offsetTop
            },
            methods: {
                searchCity(e) {
                    this.$emit('change', e.target.innerText)
                },
                touchStart() {
                    this.touchStatus = true
                },
                touchMove(e) {
                    if(this.touchStatus) {
                        if(this.timer) {
                            clearTimeout(this.timer)
                        } 
                        this.timer = setTimeout(()=>{
                            const touchY = e.touches[0].clientY - 82
                            const index = Math.floor((touchY - this.startY) / 20)
                            if(index >= 0 && index < this.letters.length) {
                                this.$emit('change', this.letters[index])
                            }
                        }, 16)
                    }
                },
                touchEnd() {
                    this.touchStatus =false
                }
            }
        }
    </script>
    
    <style type="text/css" lang="stylus" scoped>
        @import '~styles/varible.styl'
        .list
            display: flex
            flex-direction: column
            justify-content: center
            align-items: center
            position: absolute
            right: 0
            top: 1.58rem
            width: .4rem
            bottom: 0
            .item
                line-height: .4rem
                color: $bgColor
                font-size: .28rem
    </style>
    

    总结:

    • 注意点:函数节流和函数防抖都是通过减少实际逻辑处理过程的执行来提高事件处理函数运行性能的手段,并没有实质上减少事件的触发次数。

    相关文章

      网友评论

          本文标题:JS - 函数节流和函数防抖

          本文链接:https://www.haomeiwen.com/subject/zscldqtx.html