lib/debounce.js
function debounced(...args) {
        let now = + new Date(),
            remaining;


        // 获取剩余时间
        if (!lastCalled && !leading) {
            remaining = wait;
        } else {
            remaining = wait - (now - lastCalled);
        }

        // 区分是否立即执行
        if (remaining <= 0 || remaining > wait) {
            timeId && clearTimeout(timeId);
            lastCalled = now;
            result = callback.apply(this, args);
            lastContext = lastArgs = timeId = null;
        } else if (trailing) {

            // 更新参数
            lastContext = this;
            lastArgs = args;

            // 设置延时
            timeId && clearTimeout(timeId);
            timeId = setTimeout(() => {
                lastCalled = 0;
                result = callback.apply(lastContext, lastArgs);
                lastContext = lastArgs = timeId = null;
            }, wait);
        }

        // 返回结果
        return result;
    }
function debounced(...args) {
        let now = + new Date(),
            remaining;


        // 获取剩余时间
        if (!lastCalled && !leading) {
            remaining = wait;
        } else {
            remaining = wait - (now - lastCalled);
        }

        // 区分是否立即执行
        if (remaining <= 0 || remaining > wait) {
            timeId && clearTimeout(timeId);
            lastCalled = now;
            result = callback.apply(this, args);
            lastContext = lastArgs = timeId = null;
        } else if (trailing) {

            // 更新参数
            lastContext = this;
            lastArgs = args;

            // 设置延时
            timeId && clearTimeout(timeId);
            timeId = setTimeout(() => {
                lastCalled = 0;
                result = callback.apply(lastContext, lastArgs);
                lastContext = lastArgs = timeId = null;
            }, wait);
        }

        // 返回结果
        return result;
    }
function debounced ( ... args ) { let now = + new Date ( ) , remaining ; // 获取剩余时间 if ( ! lastCalled && ! leading ) { remaining = wait ; } else { remaining = wait - ( now - lastCalled ) ; } // 区分是否立即执行 if ( remaining <= 0 || remaining > wait ) { timeId && clearTimeout ( timeId ) ; lastCalled = now ; result = callback . apply ( this , args ) ; lastContext = lastArgs = timeId = null ; } else if ( trailing ) { // 更新参数 lastContext = this ; lastArgs = args ; // 设置延时 timeId && clearTimeout ( timeId ) ; timeId = setTimeout ( ( ) => { lastCalled = 0 ; result = callback . apply ( lastContext , lastArgs ) ; lastContext = lastArgs = timeId = null ; } , wait ) ; } // 返回结果 return result ; }
定义函数
定义函数