• 防抖截流装饰器的封装


    注释

    /**

    • @example @limitFrequency('debounce') @limitFrequency('throttle')
    • @params type:String enum('debounce','throttle')
    • @params wait:Number 延迟时间默认500毫秒,也可自定义传入
    • @note 支持箭头函数的写法了,且将截流throttle函数和防抖debounce函数合二为一
    • 防抖 debounce: 任务被调用后, 在一定延迟后才执行, 若再次被调用, 则重新计算延迟时间
    • 截流 throttle: 一定时间内, 任务不管被调用多少次, 只实际执行一次
      */

    箭头函数写法

        箭头函数写法 执行函数挂在 descriptor.initializer里,执行函数为return 出来的 function,且是匿名函数
    
        descriptor.initializer = function(){
            return function(){
                console.log('执行')
            }
        }
    

    普通函数写法

        普通函数写法 执行函数挂在 descriptor.value上,执行函数就是该function
        
        descriptor.value = function(){
            console.log('执行')
        }
    

    调用方式

        //上述所说的执行函数就是fn
    
        @limitFrequency('debounce',1000)
        fn = ()=>{
            console.log('执行')
        }
    

    装饰器封装

        export function limitFrequency(type, wait = 500) {
            return function (pageInstance, funcName, descriptor) {
                let timer = null;
                let cacheValue = descriptor?.value || descriptor?.initializer()
                const callBack = (...args) => {
                    if (type == 'debounce') {
                        if (timer) {
                            clearTimeout(timer);
                            timer = null;
                        }
                        timer = setTimeout(() => {
                            cacheValue.apply(this, args)
                            clearTimeout(timer);
                            timer = null; 
                        }, wait)
                    }
                    if (type == 'throttle' && !timer) {
                        timer = setTimeout(() => {
                            cacheValue.apply(this, args)
                            clearTimeout(timer);
                            timer = null;
                        }, wait)
                    }
                };
                if (cacheValue.name == funcName) {
                    descriptor.value = callBack
                } else {
                    descriptor.initializer = () => callBack;
                }
                return descriptor;
            }
        }
    

    注意:执行完函数需清除定时器且重置标志timer的值

  • 相关阅读:
    WCF Data Contract之集合类型
    LINQ To DataSet
    WCF Data Contract之枚举
    初识Parallel Extensions之TPL(二)
    初识Parallel Extensions之TPL
    java北京行之单例模式的引入
    Strut2 入门
    解决 Eclipse 下使用 Ant 编译出现问题: 警告:编码 GBK 的不可映射字符
    解决 Ant 非法字符: \65279
    [原创]Visual Studio 中引用 Flash 控件
  • 原文地址:https://www.cnblogs.com/hjj2ldq/p/12752227.html
Copyright © 2020-2023  润新知