函数防抖节流问题

1.函数防抖和函数节流都是防止某一时间频繁触发,但是这两兄弟之间的原理却不一样

2.函数防抖是某一段时间内只执行一次(如5秒内只执行一次,多次触发重新计时),而函数节流是间隔时间执行(每多少秒内执行一次,无论触发多少次,按照固定频率执行)

【函数防抖】在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

【函数节流】规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
function debounce(func,wait,immediate) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            let callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(() => {
                func.apply(context, args)
            }, wait);
        }
    }
}

  

    window.onload = function () {
            
            // 函数防抖
            var timer
            var tar = document.getElementsByTagName("input")[0];
            tar.addEventListener("keyup", function(e){
                let value = e.target.value
                console.log(timer)
                if(timer) clearTimeout(timer)
                timer = setTimeout(() => {
                    console.log({value})
                }, 2000);
            })
        }

  

        window.onload = function () {
            
            // 函数节流
            var timer = null
            var tar = document.getElementsByTagName("input")[0];
            tar.addEventListener("keyup", function(e){
                var value = e.target.value
                if(!timer){
                    timer = setTimeout(() => {
                        timer = null
                        clearTimeout(timer)
                        console.log({value})
                    },2000)
                }
            })

        }    

  

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 */
function throttle(func, wait ,type) {
    if(type===1){
        let previous = 0;
    }else if(type===2){
        let timeout;
    }
    return function() {
        let context = this;
        let args = arguments;
        if(type===1){
            let now = Date.now();

            if (now - previous > wait) {
                func.apply(context, args);
                previous = now;
            }
        }else if(type===2){
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null;
                    func.apply(context, args)
                }, wait)
            }
        }

    }
}

  

 

posted @ 2019-04-18 08:40  winyh  阅读(326)  评论(0编辑  收藏  举报