节流与防抖

节流 : 每隔一定时间执行一次

    function throttle(fn, delay) {
        let timer = null;
        return () => {
            if (timer) {
                return;
            };
            timer = setTimeout(() => {
                fn();
                timer = null;
            }, delay)
        }
    }

    function sole() {
        console.log("触发了")
    }
    window.onscroll = throttle(sole, 500);

防抖 : 等待一定时间然后执行一次,若等待时间内再次触发,则等待时间重置

    function debounce(fn, delay) {
        let timer = null
        return () => {
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(fn, delay) 
        }
    }

    function sole() {
        console.log("触发了")
    }
    window.onscroll = debounce(sole, 500);

 

posted @ 2022-03-23 15:54  sprite692  阅读(27)  评论(0)    收藏  举报