工作生活

js节流

2019-07-02  本文已影响0人  GGatsby

function throttle(func, wait) {

var timeout, context, args, result;

var previous = 0;

var later = function() {

    previous = new Date();

    timeout = null;

    func.apply(context, args)

};

    var throttled = function() {

    var now = new Date();

    //下次触发 func 剩余的时间

    var remaining = wait - (now - previous);

    context = this;

    args = arguments;

    // 如果没有剩余的时间了或者你改了系统时间

    // 第一次立即请求,增强了节流

    if (remaining <= 0 || remaining > wait) {

        if (timeout) {

            clearTimeout(timeout);

            timeout = null;

        }

        previous = now;

        func.apply(context, args);

    } else if (!timeout) {

        timeout = setTimeout(later, remaining); 

    }

};

return throttled;

}

另一个版本:

第一次立即请求,但是每一秒请求一次,最后一次请求保留

function throttle(func, wait) {

    var timeout, context, args, result;

    var previous = 0;

    var later = function() {    

        previous = new Date();    

        timeout = null;    

        func.apply(context, args)

    };    

        var throttled = function() {    

            var now = new Date();    

            //下次触发 func 剩余的时间    

            var remaining = wait - (now - previous);    

            context = this;    args = arguments;    

            // 如果没有剩余的时间了或者你改了系统时间   

            // 第一次立即请求,增强了节流    

            if (remaining <= 0 || remaining > wait) {       

                 if (timeout) {            

                    clearTimeout(timeout);            

                    timeout = null;        

                 }        

                previous = now;        

                func.apply(context, args);   

            } else {     

                // 清除之前的定时器

                if (!timeout){clearTimeout(timeout)}

                timeout = setTimeout(later, remaining);     

            }

         };

    return throttled;

}

上一篇下一篇

猜你喜欢

热点阅读