美文网首页
函数的节流和防抖

函数的节流和防抖

作者: 风雅欢乐 | 来源:发表于2020-05-02 18:53 被阅读0次

    防抖(debounce)

    函数的防抖)指的是, 在持续触发事件时, 当一定时间内没有在触发, 事件处理函数才会执行一次, 如果设定时间到来之前又触发, 则重新延迟.

    function debounce(fn, delay) {
        let timer;
        
        return function (...args) {
            const that = this;
            
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            
            timer = setTimeout(function() {
                fn.apply(that, args);
                timer = null;
            }, delay);
        }
    }
    

    节流(throttle)

    节流指的是, 当持续触发事件时, 保证一定时间段内只调用一次事件处理函数

    function throttle(fn, duration) {
        let timer = null;
        let lasttime = Date.now();
        
        return function (...args) {
            const that = this;
            const nowtime = Date.now();
            const remaining = duration - (nowtime - lasttime);
            
            if (timer) {
                clearTimeout(timer);            
            }
            
            if (remaining <= 0) {
                fn.apply(that, args);
                lasttime = nowtime;
            }
            
            timer = setTimeout(function () {
                fn.apply(that, args);
                timer = null;
            }, remaining);
        }
    }
    

    相关文章

      网友评论

          本文标题:函数的节流和防抖

          本文链接:https://www.haomeiwen.com/subject/ndflghtx.html