zoukankan      html  css  js  c++  java
  • 节流阀,防抖动函数

        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)
                }
            }
        }
    
        //以上三个函数,其实都是闭包的应用,
        //现在,如果别人在问完你闭包特点等问题之后,再问你实际的应用场景,那么你可以列举出以上三个函数。
  • 相关阅读:
    kyeremal-bzoj2038-[2009国家集训队]-小z的袜子(hose)-莫队算法
    移位操作之旋转移位
    leetcode 二分查找 Search in Rotated Sorted Array
    背包算法练习--求小于某数字的数组最大和:
    Splunk 会议回想: 大数据的关键是机器学习
    CSDN个人空间、问答频道停站维护公告
    HDFS主要节点解说(一)节点功能
    24点
    【Nginx】事件驱动框架和异步处理
    OC中字符串的提取与替换-四种不同方法实现
  • 原文地址:https://www.cnblogs.com/hjj2ldq/p/10437055.html
Copyright © 2011-2022 走看看