函数防抖和函数节流(分流)

(1)啥是函数防抖:

        函数防抖就是一个函数被多次触发,但是我们只需要执行一次。

    实现方式:

       
     < div id= "toCli" >反反复复 </ div >;    
< script >
        var timer;
var fo = document. getElementById( "toCli")
function fun(){
console. log( "啊 沙鑫好帅123123啊 ")
}
fo. onmousemove = function(){
clearTimeout( timer)
var timer = setTimeout( fun(), 500)
}

    差不多就是这个意思 ;但是这么写的话每次鼠标滑动 函数执行之后这个timer都会被销毁,

    所以封装一下这个函数:

        var obj = document. getElementById( "toCli")
function fun(){
console. log( "啊 沙鑫好帅啊 ")
}
function debounce( method, delay, context) {
clearTimeout( method. timer);
method. timer = setTimeout( function () {
method. call( context);
}, delay);
}
obj. onmousemove = function () {
debounce( fun, 50);
};

(2)啥是函数节流(分流):

        函数节流(分流)就是这个函数在预算时间内必须执行一次,但是要函数防抖

    function throttle( method, delay, mustRunDelay) {
var timer = null, args = arguments;
var start = 0, now = 0;
return function () {
var context = this;
now= Date. now();
if(! start){
start = now;
}
if( now - start >= mustRunDelay){
method. apply( context, args);
start = Date. now();
} else {
clearTimeout( timer);
timer = setTimeout( function () {
method. apply( context, args);
}, delay);
}

}
}
obj. onmousemove = throttle( myFun, 50, 500);


猜你喜欢

转载自blog.csdn.net/weixin_38641550/article/details/80753285