zoukankan      html  css  js  c++  java
  • 防抖和节流

    <!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>
  • 相关阅读:
    Nginx Record
    Go 查找元素
    博客转移公告
    模板库
    模板库
    【BZOJ2276】Temperature
    【BZOJ3524】Couriers
    【BZOJ4458】GTY的OJ
    AtCoder Grand Contest 007
    Editing 2011-2012 ACM-ICPC Northeastern European Regional Contest (NEERC 11)
  • 原文地址:https://www.cnblogs.com/whlBooK/p/13685227.html
Copyright © 2011-2022 走看看