SOURCE

console 命令行工具 X clear

                    
>
console
// debounce-非立即执行版本
function debounce1(func, wait) {
    let timer;
    return function() {
        const context = this;
        const args = arguments;
        if(timer) {
           clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(context, args);
        }, wait);
    }
}

// debounce-立即执行版本
function debounce2(func, wait) {
    let timer;
    return function() {
        const context = this;
        const args = arguments;
        let callNow = !timer;
        timer = setTimeout(()=>{
            timer = null;
        }, wait);
        if (callNow) {
            func.apply(context, args);
        }
    }
}

// throttle-计时器版
function throttle1(func, wait) {
    let timer;
    return function() {
        const context = this;
        const args = arguments;
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                func.apply(context, args);
            }, wait)   
        }
    }
}
// throttel-时间戳版
function throttle2(func, wait) {
    let pre = 0;
    return function() {
        const context = this;
        const args = arguments;
        let now = new Date().getTime();
        if (now - pre > wait) {
            func.apply(context, args);
            pre = now;
        }
    }
}

// handler Test
function handler1() {
    console.log("debounce非立即执行");
}

function handler2() {
    console.log("debounce立即执行");
}

function handler3() {
    console.log("throttle 定时器");
}

function handler4() {
}
<button class="btn" onclick="debounce2(handler1, 1000)">debounce非立即执行</div>
<button class="btn" onclick="debounce2(handler2, 1000)">debounce立即执行</div>
<button class="btn" onclick="throttle1(handler3, 1000)">throttle 定时器</div>
<button class="btn" onclick="throttle2(handler4, 1000)">throttle 时间戳</div>
.btn {
    display: block;
    margin-top: 10px;
    width: 200px;
    height: 44px;
    background: yellowgreen;
    outline: none;
    border: none;
    border-radius: 6px;
    color: aliceblue;
    line-height: 44px;
    text-align: center;
}