防抖和节流的最通俗的解释

100 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

看了很多网上的案列,对防抖和节流的理解还不是透彻,某天看到一个评论,突然就醍醐灌顶了

image.png

附上防抖和节流的代码

防抖

function debounce(func, delay) {
    var timeout;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(()=>{
            func.apply(this, arguments);
        }, delay);
    }
}

节流

function throttle(fn, delay = 500) {
        let timer = null
        return function () {
            if (!timer) {
                fn.apply(this, arguments)
                timer = setTimeout(function () {
                    timer = null;
                }, delay)
            } else {
                console.log("你还不能执行哦")
            }
        }
    }