debounce

function Debounce(wait: number, immediate: boolean = false) {
    return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
        let timeout: any;
        const originalMethod = descriptor.value;
        descriptor.value = function (...args: any[]) {
            let context = this;
            let later = function () {
                timeout = null;
                if (!immediate) {
                    originalMethod.apply(context, args)
                }
            }
            let callNow = immediate && !timeout;
            clearTimeout(timeout)
            timeout = setTimeout(later, wait);
            if (callNow) {
                originalMethod.apply(context, args)
            }
        }

        return descriptor;
    }
}


class MouseObj {

    @Debounce(1000)
    public print() {
        console.log(1)
    }
}


(window as any)["MouseObj"] = MouseObj

 

posted @ 2019-07-05 18:47  MakeCoder  阅读(229)  评论(0编辑  收藏  举报