函数节流和函数防抖

<!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>
    <style>

    </style>
</head>

<body>
    
    <input id='InputVal' type="text" placeholder="函数防抖">
    <button id='btn'>函数节流</button>
    <button id='btn2'>函数节流btn2</button>

    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>


        /**
         * 函数防抖:在固定时间内,多次触发,只触发最近的一次
         * 应用场景: 实时搜索、拖拽
        */
        function shake(func, time) {
            var timer = null;
            return function () {
                var _this = this;
                var _arg = arguments;
                clearTimeout(timer);
                timer = setTimeout(function () {
                    func.apply(_this, _arg)
                }, time)
            }
        }

        function watchInput(e) {
            console.log(e)
        }

        InputVal.oninput = shake(watchInput, 1000);


        /**
         * 函数节流,指在固定时间内,多次触发,只触发最开始的那一次
         * 应用场景: 用户疯狂点击、
        */
        function Thorttle(func, time) {
            var lastTime = 0;
            return function () {
                var nowTime = new Date().getTime();
                if (nowTime - lastTime >= time) {
                    lastTime = nowTime;
                    func.apply(this, arguments);
                }
            }
        }

        var a = 50, b = 60;
        function func(a, b) {
            console.log(a, b)
        }

        var test = Thorttle(func, 5000);
        $('#btn').click(function (e) {
            test(e, a, b);
        })


        var test2 = Thorttle(func, 2000);
        $('#btn2').click(function (e) {
            test2(e)
        })
    </script>
</body>

</html>

你可能感兴趣的:(前端随笔)