• 防抖和节流


    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
    
        <body>
            <script type="text/javascript">
                // 防抖(debounce):触发高频事件后 n 秒内函数只会执行一次,如果 n 秒内高频事件再次被触发,则重新计算时间
    
                // 举例:就好像在百度搜索时,每次输入之后都有联想词弹出,这个控制联想词的方法就不可能是输入框内容一改变就触发的,他一定是当你结束输入一段时间之后才会触发。
                function debounce(fn, wait) {
                    let timer = null;
                    return function() {
                        let arg = arguments;
                        if(timer) {
                            clearTimeout(timer);
                            timer = null;
                        }
                        timer = setTimeout(() => {
                            fn.apply(this, arguments)
                        }, wait)
                    }
                }
    
                function clg() {
                    console.log('clg')
                }
                window.addEventListener('resize', debounce(clg, 1000))
                // 节流函数:将多次执行变成每隔一个时间节点去执行的函数
                // 举例:预定一个函数只有在大于等于执行周期时才执行,周期内调用不执行。就好像你在淘宝抢购某一件限量热卖商品时,你不断点刷新点购买,
                //可是总有一段时间你点上是没有效果,这里就用到了节流,就是怕点的太快导致系统出现bug。
                function throttle(fn, time) {
                    let lastTime = true;
                    return function() {
                        if(!lastTime) {
                            return false
                        }
                        lastTime = false;
                        setTimeout(() => {
                            fn()
                            lastTime = true;
                        }, time)
                        //  let nowTime = Date.now();
                        //  console.log(nowTime - lastTime)
                        //  if(nowTime - lastTime > time){
                        //    fn();
                        //    last = nowTime
                        //  }
                    }
                }
    
                function sayHi() {
                    console.log('hi')
                }
    
                setInterval(throttle(sayHi, 5000), 500)
            </script>
        </body>
    
    </html>
  • 相关阅读:
    Mac item 远程连接服务器
    搭建私人Git Server
    数据结构第三章小结
    第二章实践小结
    poj3617 Best Cow Line
    最长上升子序列问题
    Uva11450 Wedding shopping
    poj3050 hopscotch
    poj2718 Smallest Difference
    poj3669 Meteor Shower
  • 原文地址:https://www.cnblogs.com/whlBooK/p/13685227.html
Copyright © 2020-2023  润新知