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节流函数

    JS节流函数 1. 节流函数的定义 2. 节流函数的用法

  • 前端性能优化-浅谈js防抖和节流

    浅谈js防抖和节流

  • js节流

  • js节流

    function throttle(func, wait) { var timeout, context, ...

  • JS 节流

    Throttling and debouncing in JavaScript Debounce Deep Div...

  • js节流

    节流(throttle) 第一步 实现一个函数,返回一个函数func参数,第一个参数是一个函数,第二个参数是一个数...

  • 防抖和节流

    一、防抖:只执行最后一次 js防抖方法 一、节流:控制执行次数 节流

  • 微信小程序防抖、节流的使用

    1、防抖、节流函数的封装 在utils文件夹下新建utils.js文件,然后写入节流和防抖函数 在.js页面引入并使用:

  • js函数节流、防抖

    js 函数节流、防抖 新建index.js将下面代码复制到index.js中

  • 函数防抖和节流

    前言:函数防抖和函数节流都是用于优化高频率执行js的一种手段 节流 函数节流:是指一定时间内js方法只跑一次应用场...

网友评论

    本文标题:js节流

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