美文网首页
函数防抖、节流

函数防抖、节流

作者: INGME | 来源:发表于2022-01-13 11:35 被阅读0次

    函数防抖:n秒内只要触发事件,就重新计时,事件处理函数的程序将永远不会被执行

    /**
     * 函数防抖
     * @param  {[fn]} 回调方法
     * @param  {[time]} 延迟时间
     * @param  {[immediate]} 是否立即执行
     */
    
    function debounce(fn, time, immediate) {
        var timer = null,
            result;
    
        var debounced = function() {
             var context = this,
                 args = arguments;
    
            if(timer) clearTimeout(timer);
        
            if(immediate) {
                // 如果已执行,不再执行
               var callNow = !timer;
               timer = setTimeout(function() {
                    timer = null;
                }, time);
                if(callNow) {
                    result = fn.apply(context, args);
                }
            } else {
                timer = setTimeout(function() {
                   result = fn.apply(context, args);
                }, time)
            }
            return result;
        }
        
        debounced.cancel = function() {
            clearTimeout(timer);
            timer = null;
         }
    
        return debounced;
    }
    

    函数节流:事件被触发,n秒内只执行一次事件处理函数

    /**
     * 函数节流
     * @param  {[fn]} 回调方法
     * @param  {[delay]} 延迟时间
     */
    
    function throttle(fn, delay) {
        var timer = null,
            begin = new Date().getTime();
    
        return funcion() {
            var context = this,
                args = arguments,
                now = new Date().getTime();
    
            clearTimeout(timer);
    
            if(now - begin >= delay) {
                fn.apply(context, args);
                begin = now;
            } else {
                timer = setTimeout(function() {
                    fn.apply(context, args);
                }, delay)
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:函数防抖、节流

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