函数节流与防抖

函数防抖:

让某个函数在上一次的执行后满足等待某个时间内不再触发此函数后再执行,再等待时间内再次触发此函数,等待时间会重新计算。比如防止提交按钮时的多次点击。

代码:

_.debounce = (func, wait, immediate) => {  //func为需要防抖的函数 wait为等待时间 immediate为true,函数调用时就会执行一次func
            var timeout, args, context, timestamp, result;
            var later = () =>{
                var last = _.now() - timestamp;
                if(last < wait && last >= 0){
                    timeout = setTimeout(later, wait-last);
                }else{
                    timeout = null;
                    if(!immediate){
                        result = func.apply(context, args);
                        if(!timeout){
                            context = args = null;
                        }
                    }
                }
            }
            return () => {
                context = this;
                args = arguments;
                timestamp = _.now();
                var callnow = immediate && !timeout;
                if(!timeout){
                    result = func.apply(context, args);
                    context = args = null;
                }
                return result;
            }
        }

函数节流:

每间隔某个时间去执行某个函数,避免函数的过多执行。比如监听滚动条事件,滚动条每次改变都会执行这个函数,太频繁。

function throthe(func, context){
            clearTimeout(func, tId);  //重点是要清除上次的计时器
            func.tId = setTimeout(function (){
                func.call(context);
            },1000)
}

猜你喜欢

转载自blog.csdn.net/baibaider/article/details/82148795