# 防抖和节流

# debounce(防抖)

在连续触发的事件只响应最后一次

# 示例说明

输入框,输入结束后进行网络请求

# 简单实现

function debounce(func, time) {
    let handler = null;
    return (...arg) => {
        if (handler) {
            window.clearTimeout(handler);
        }
        handler = setTimeout(() => {
            func.apply(arg);
        }, time);
    }
}

# throttle(节流)

一定时间内连续触发的时间,只响应一次

# 示例说明

监听mousemove时,多时间内会触发多次,只需要执行一次就行

# 简单实现

function throttle(func, time) {
    const getNow = () => Date.parse(new Date);
    let lastTime = -1;
    return (...arg) => {
        if (lastTime === -1) {
            lastTime = getNow();
        }
        if (getNow() - lastTime >= time) {
            func.apply(arg);
            lastTime = -1;
        }
    }
}