SOURCE

console 命令行工具 X clear

                    
>
console
/**
 * 防抖函数,高频函数触发后n秒内只执行一次,当n秒内再次被触发时重新开始计时。
 * 防抖防抖,就是停止抖动后才执行事件处理函数,并且最终只执行1次。
 */
function debounce(fn, ms) {
    let timerId;
    return function () {
        timerId && clearTimeout(timerId);
        timerId = setTimeout(() => {
            fn.apply(this, arguments);
        }, ms);
    }
}

/**
 * 节流函数,高频函数触发,每n秒只执行一次,节流函数会稀释函数的执行频率。
 * 节流节流,就是流量达到一定程度才执行,每n秒只执行1次。
 */
function throttle(fn, ms) {
    let timerId;
    return function () {
        if (!timerId) {
            timerId = setTimeout(() => {
                timerId = null;
                fn.apply(this, arguments);
            }, ms);
        }
    }
}


//防抖对比测试
$(function () {
    $("#no-debounce").keyup((e) => {
        console.log(e.target.value);
    });
    $("#debounce").keyup(debounce((e) => {
        console.log(e.target.value);
    }, 500));
})

//节流对比测试
$(function () {
    $("#no-throttle").mousemove((e) => {
        console.log("clientX:" + e.clientX + ", clientY:" + e.clientY);
    });
    $("#throttle").mousemove(throttle((e) => {
        console.log("clientX:" + e.clientX + ", clientY:" + e.clientY);
    }, 500));
})
<!--防抖-->
不防抖:<input id="no-debounce" />
防抖:<input id="debounce" />


<hr>

<!--节流-->
节流:<div id="no-throttle" style="width:300px; height:100px; background:#ff0000"></div>
节流:<div id="throttle" style="width:300px; height:100px; background:#ff00ff"></div>

本项目引用的自定义外部资源