zoukankan      html  css  js  c++  java
  • 学习笔记 -- js节流函数

     /*
     * 频率控制 返回函数连续调用时,fn 执行频率限定为每多少时间执行一次
     * @param fn {function}  需要调用的函数
     * @param delay  {number}    延迟时间,单位毫秒
     * @param immediate  {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。
     * @return {function}实际调用函数
     */
    commFun.throttle = function (fn,delay, immediate, debounce) {
        var curr = +new Date(),//当前时间
            last_call = 0,
            last_exec = 0,
            timer = null,
            diff, //时间差
            context,//上下文
            args,
            exec = function () {
                last_exec = curr;
                fn.apply(context, args);
            };
        return function () {
            curr= +new Date();
            context = this,
                args = arguments,
                diff = curr - (debounce ? last_call : last_exec) - delay;
            clearTimeout(timer);
            if (debounce) {
                if (immediate) {
                    timer = setTimeout(exec, delay);
                } else if (diff >= 0) {
                    exec();
                }
            } else {
                if (diff >= 0) {
                    exec();
                } else if (immediate) {
                    timer = setTimeout(exec, -diff);
                }
            }
            last_call = curr;
        }
    };
    
    /*
     * 空闲控制 返回函数连续调用时,空闲时间必须大于或等于 delay,fn 才会执行
     * @param fn {function}  要调用的函数
     * @param delay   {number}    空闲时间
     * @param immediate  {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。
     * @return {function}实际调用函数
     */
    
    commFun.debounce = function (fn, delay, immediate) {
        return commFun.throttle(fn, delay, immediate, true);
    };

     简易版:

    /*js节流函数*/
    commFun.throttle = function (fn, delay) {
        var timer = null;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay ? delay : 200);
        };
    };
  • 相关阅读:
    php根据时间显示刚刚,几分钟前,几小时前的实现代码
    PHP中获取当前页面的完整URL
    PhpExcel中文帮助手册|PhpExcel使用方法
    洛谷P1781 宇宙总统【排序+字符串】
    洛谷P1579 哥德巴赫猜想(升级版)【水题+素数】
    洛谷P1478 陶陶摘苹果(升级版)【水题】
    洛谷P1002 过河卒【dp】
    51Nod
    排序算法总结(C++)
    UVA1339
  • 原文地址:https://www.cnblogs.com/mrxia/p/4554950.html
Copyright © 2011-2022 走看看