美文网首页
前端性能优化——防抖

前端性能优化——防抖

作者: 发发呆哟 | 来源:发表于2020-05-24 16:02 被阅读0次

    在开发中经常会遇到频繁触发的事件
    如onScroll,onChange等,当这些频繁触发的事件和请求相关联的时候,每次触发都去发请求会造成巨大的服务器压力,比如简书的实时保存,都是等待onKeyUp事件后500ms左右去执行的save操作。
    由此我们需要实现一个防抖函数,当频繁触发的事件,停止某个时间后,触发函数
    思路:建立一个定时器,如果触发事件,则取消定时器,直到定时器执行,循环往复,这个防抖函数在我看来,很像装饰器,对函数进行了强化
    注意点:针对防抖的操作,需要直接调用强化后函数

    第一个例子,onMouseMove

    当鼠标滑过某个区域后,停止滑动后,500ms,计数器加一
    第一版代码如下

    import React from 'react';
    import { debounce } from '@/util/plugins'
    import './index.scss'; // 样式随便写个矩形区域就行
    
    class Debounce extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                count: 1,
            }
            this.onMouseMove = debounce(this.onMouseMove, 500);
        }
    
        onMouseMove = () => {
            this.setState(prev => ({
                count: prev.count + 1
            }), () => {
                console.log(this.state)
            })
        }
    
        render() {
            return <div className="debounce-wrap" onMouseMove={this.onMouseMove} ></div>
        }
    }
    
    export default Debounce;
    
    export const debounce = (fn, wait) => {
        let timeout = null
        return () => {
            clearTimeout(timeout)
            timeout = setTimeout(()=>{
                fn()
            }, wait)
        }
    }
    

    第二份例子,onChange

    上面的例子实现了,滑动停止后500ms,执行计数器+1操作,这次我们对onChange这个需要挂参数的例子进行实现
    需要实现的效果:input输入文字后,1s后显示在页面上
    第二版,需要把参数带过去

    import React from 'react';
    import { debounce } from '@/util/plugins'
    
    class Debounce extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                text: '',
                cloneText: ''
            }
            this.setCloneText = debounce(this.setCloneText, 1000);
        }
    
        onChange = (value) => {
            this.setState({text: value}, ()=>{
                this.setCloneText(value)
            })
        }
    
        setCloneText = text => {
            this.setState({ cloneText: text })
        }
    
    
        render() {
            return <React.Fragment>
                <input value={this.state.text} onChange={e => this.onChange(e.target.value)} />
                <p>{this.state.cloneText}</p>
            </React.Fragment>
        }
    }
    
    export default Debounce;
    
    export const debounce = (fn, wait) => {
        let timeout = null
        return (...args) => {
            clearTimeout(timeout)
            timeout = setTimeout(()=>{
                fn(...args)
            }, wait)
        }
    }
    

    小结

    在第二版,可以通过...扩展运算符将agrs(数组)转换成函数参数,同时我们在日常开发中一直用的是箭头函数,this指向问题已经被解决,为了兼容低版本语法,所以我们有第三版

    // 防抖
    export const debounce = (fn, wait) => {
        let timeout = null
        
        return (...args) => {
            clearTimeout(timeout)
            var context = this;
            timeout = setTimeout(()=>{
                fn.apply(context, args)
            }, wait)
        }
    }
    

    第三份例子,防止短时间内重复点击

    这是在写RN的时候遇到的问题,在点击RN页面的时候,快速多次点击页面功能,可能会唤起多个webView,导致用户体验极差,用户的本意是只想唤起一起某个页面,当时我处理的方案是写了一个高阶组件,处理这个问题,不过其核心点还是防抖函数
    上面已经完成的,是在用户多次触发停止后,n个时间后触发函数
    我们的需求修改为事件直接触发,如果n时间内又触发,则不执行,知道n时间后,变为可触发

    import React from 'react';
    import { debounce } from '@/util/plugins'
    import './index.scss';
    
    class Debounce extends React.Component {
        constructor(props) {
            super(props)
            this.state = { }
            this.clickBtn = debounce(this.clickBtn, 10000, true)
        }
    
        clickBtn = () => {
            console.log('click')
        }
    
    
        render() {
            return <React.Fragment>
                <button onClick={this.clickBtn}>开心按钮</button>
            </React.Fragment>
        }
    }
    
    export default Debounce;
    
    
    // 防抖--防止重复触发
    export const debounce = (fn, wait, immediate) => {
      var timeout = null;
      return (...args) => {
        var context = this;
        if(immediate){
          let callNow = !timeout;
          //  建立计时器,设定timeout后失效
          timeout = setTimeout(()=>{timeout = null;}, wait)
           // 如果不存在计时器,表面可以直接执行
          if(callNow) fn.apply(context, args)
          
        } else {
          clearTimeout(timeout)
          timeout = setTimeout(()=>{ fn.apply(context, args) }, wait)
        }
      }
    }
    

    第三份例子强化,解除防抖

    还是在RN里遇到的,如果webview已经被新开了,我们就应该把锁定的重复点击关闭,当然重新触发点击的时候,我们的防抖又会被启动

    import React from 'react';
    import { debounce } from '@/util/plugins'
    import './index.scss';
    
    class Debounce extends React.Component {
        constructor(props) {
            super(props)
            this.state = { }
            this.clickBtn = debounce(this.clickBtn, 10000, true)
        }
    
        clickBtn = () => {
            console.log('click')
        }
    
    
        render() {
            return <React.Fragment>
                <button onClick={this.clickBtn}>开心按钮</button>
                <button onClick={()=>{this.clickBtn.cancal()}}>解除按钮</button>
            </React.Fragment>
        }
    }
    
    export default Debounce;
    
    
    export const debounce = (fn, wait, immediate) => {
        var timeout = null
        
        var debounced = (...args) => {
            clearTimeout(timeout)
            var context = this;
            if(immediate){
                // 如果计时器不存在,就立即执行,计数器在wait秒后解除
                let callNow = !timeout
                timeout = setTimeout(()=>{
                    timeout = null
                }, wait)
                if(callNow){
                    fn.apply(context, args)
                }
            }else{
                timeout = setTimeout(()=>{
                    fn.apply(context, args)
                }, wait)
            }
        }
    
        debounced.cancal = () => {
            clearTimeout(timeout)
            timeout = null
        }
    
        return debounced
    }
    

    相关文章

      网友评论

          本文标题:前端性能优化——防抖

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