• 函数防抖和节流


    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    
    <body>
        <div id="btn">点我啊</div>
    </body>
    <script>
        //每wait时间执行一次
        function throttle(func, wait) {
            var timeout = null;
            var previous = null;
            return function () {
                var now = +new Date();
                var context = this;
                if (!previous) {
                    previous = now
                }
                //下次触发 func 剩余的时间
                var remaining = wait - (now - previous);
                // 如果小于0,说明离上次触发超过了wait时间,重新算
                if (remaining < 0) {
                    remaining = wait
                }
                if (!timeout) {
                    timeout = setTimeout(() => {
                        previous = +new Date();
                        timeout = null;
                        func.apply(context, arguments)
                    }, remaining);
                }
            };
        }
        ////无论wait时间内执行多少次,只会在最后一次的wait时间后执行
        function debounce(fn, wait) {
            var timeout = null;
            return function () {
                var context = this;
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(() => {
                    fn.apply(context, arguments)
                }, wait)
            }
        }
        // function debounce(fn, wait, immediate) {
        //     var timeout = null;
        //     var first = true;
        //     return function () {
        //         var context = this;
        //         if (immediate && first) {
        //             fn.apply(context, arguments)
        //             first = false
        //         }
        //         if (timeout) clearTimeout(timeout);
        //         timeout = setTimeout(() => {
        //             fn.apply(context, arguments)
        //         }, wait)
        //     }
        // }
        function say() {
            var args = Array.prototype.slice.call(arguments)
            console.log(new Date())
            console.log('参数:', args.join(','))
        }
        var a = debounce(say, 3000, true)
        document.getElementById('btn').onclick = () => {
            a('hello', 'world')
        }
    </script>
    
    </html>
    
  • 相关阅读:
    Android 剪贴板操作方法在不同版本API下的使用
    Android android:persistentDrawingCache的几个默认属性值介绍
    android 4.0 external下功能库说明
    Android gc overhead limit exceeded
    android onTerminate()方法调用需要注意的点
    android onTrimMemory()和onLowMemory()
    思维游戏(3)之时间问题
    思维游戏(2)之几根蜡烛
    思维游戏之分辨姐妹(1)
    如何根据用例图写出用例描述
  • 原文地址:https://www.cnblogs.com/fazero/p/11257188.html
Copyright © 2020-2023  润新知