节流阀,防抖动函数

    function debounce(fn,delay,immediate=false){//防抖动
        var timer
        return function () {
            var context = this
            var arg = arguments
            if(timer && !immediate){
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn(arg)
            }, delay);
        }
    }
    //初始化 debounce(() => console.log(new Date().getTime()), 2000) 改函数已经执行了
    // 相当于监听click执行的事件是debounce内部return出来的 匿名 function
    document.addEventListener('click', debounce(() => console.log(new Date().getTime()), 2000), false)
    
    function throttle(fn, threshhold) { //节流阀
        // 记录上次执行的时间
        var last
        // 定时器
        var timer
        // 默认间隔为 250ms
        threshhold || (threshhold = 2500)
        // 返回的函数,每过 threshhold 毫秒就执行一次 fn 函数
        return function () {
            var context = this
            var args = arguments
            var now = new Date().getTime()
            // 如果距离上次执行 fn 函数的时间小于 threshhold,那么就放弃
            // 执行 fn,并重新计时
            if (last && now < (last + threshhold)) {
                clearTimeout(timer)
                // 保证在当前时间区间结束后,再执行一次 fn
                timer = setTimeout(function () {
                    last = now
                    fn.apply(context, args)
                }, threshhold)
            // 在时间区间的最开始和到达指定间隔的时候执行一次 fn
            } else {
                last = now
                clearTimeout(timer)
                fn.apply(context, args)
            }
        }
    }
    // function fn(){
    //     console.log('333')
    // }
    // document.addEventListener('click', throttle(fn,2500), false)

    //类似的其实还有这种函数,和vue的once api 原理是一样的
    function once (fn){
        let called = false
        return function () {
            if (!called) {
            called = true
            fn.apply(this, arguments)
            }
        }
    }

    //以上三个函数,其实都是闭包的应用,
    //现在,如果别人在问完你闭包特点等问题之后,再问你实际的应用场景,那么你可以列举出以上三个函数。
原文地址:https://www.cnblogs.com/hjj2ldq/p/10437055.html