js节流

作者: GGatsby | 来源:发表于2019-07-02 16:55 被阅读0次

    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;

    }

    相关文章

      网友评论

        本文标题:js节流

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