防抖与节流

https://hzu-zuoxiong.gitbooks.io/frontend_note/javascript/fang-dou-yu-jie-liu.html

https://www.nowcoder.com/discuss/296979

防抖与节流函数是一种最常用的高频触发优化方式,能对性能有较大的帮助。

debounce vs throttle

二者根本的区别在于throttle保证了在每个delta T内至少执行一次,而debounce没有这样的保证


防抖(debounce):多次高频操作优化为只在最后一次执行,通常使用场景:用户输入、在输入完成后做一次输入校验、输入联想。

很多场景会频繁触发事件或频繁向后台发送请求,从而引发性能问题甚至导致浏览器奔溃。防抖要做的就是短时间内触发同一个事件,只执行最后一次,或者只在开始时执行,中间不执行

Here's the basic JavaScript debounce function (as taken from Underscore.js):

//Returns a function, that, as long as it continues to be invoked, will not be triggered. 

//The function will be called after it stops being called for N milliseconds. 

//If `immediate` is passed, trigger the function on the leading edge, instead of the trailing.

function debounce(fn, wait, immediate){

    let timer=null;

    return function(){

        let args = arguments;

        let ctx= this;


        //首次即触发

        if(immediate){

            var callNow=!timer;

            //如果已执行过,N秒内不再执行

            if(callNow){

                fn.apply(ctx,args);

                timer=setTimeout(function(){

                    timer=null;//允许N秒后再次执行

                },wait);

            }


        }else{

            if(timer){clearTimeout(timer);} //取消前次计时

            timer= setTimeout(()=>{            

                fn.apply(ctx, args);//N秒之内不触发

            }, wait);

        }


    }

}


节流(throttle):降低频率每隔一段时间执行一次,将高频操作优化成低频操作,通常使用场景:scroll、resize,通常每隔100~500ms执行一次即可。

页面滚动加载数据

当页面滚动到底部时,触发Ajax请求数据;页面滚动频繁时可能出现上个请求还未结束又开始了一个新的请求,这时就需要用节流了。

function throttle(fn, delay, immediate){

    let timer =null;

    return function(){

        let context =this;

        let args =arguments;


        let callNow = immediate;

        if(callNow){

            fn.apply(context, args);

            callNow =false;

        }


        if(!timer) {

            timer = setTimeout(()=>{

                fn.apply(context, args);

                timer =null; //允许下次计时调用函数

            }, wait); 

        }


    }

}


节流中this和arguments作用

防抖和节流函数传参用apply还是call

实现1个throttle(work, interval)包装work方法,使work方法在interval间隔内最多执行1次

function throttle(fn,wait){

    let timer = null;

    return function(){

        let ctx = this;

        let args = arguments;


        if(!timer){

            timer = setTimout(()=>{

                 fn.apply(ctx,args)

                timer = null

            },wait)

        }

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。