SOURCE

/**
 * 在wait秒内最多执行func一次
 */
// function throttle(func, wait) {
//     const self = this;
//     let lastTime = new Date();
//     return function() {
//         if (new Date().valueOf() - lastTime >= wait) {
//             func.apply(self, arguments);
//             lastTime = new Date();
//         }
//     }
// }

function throttle(func, wait) {
    let self = this;
    let timer = null;
    let lastExec = 0;

    function wrapper() {
        const args = arguments;
        const elapsed = new Date().valueOf() - lastExec;

        function exec() {
            lastExec = new Date().valueOf();
            func.apply(self, args);
        }

        clearTimeout(timer);

        if (elapsed > wait) {
            exec();
        } else {
            timer = setTimeout(exec, wait - elapsed);
        }

        clearTimeout();
    }
    return wrapper;
}


function print() {
    console.log('hello', new Date());
}

const thr = throttle(print, 3000);
const thr_ = _.throttle(print, 3000);

thr();
setTimeout(()=>{
    thr();
}, 0);
setTimeout(()=>{
    thr();
}, 4000);
setTimeout(()=>{
    thr();
}, 8000);
// setInterval(thr_, 100);
console 命令行工具 X clear

                    
>
console