[JavaScript] 防抖函数debounce的实现及其应用

2019-03-05  本文已影响0人  jiansheng
<!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>debounce</title>
</head>

<body>
    <button id="btn_0">simple button</button>
    <button id="btn_1">debounce button</button>
    <button id="btn_2">debounce button(immediate)</button>
    <script>
        (function () {
            function debounce(fn, wait = 300, immediate = false) {
                let timerId = null;

                return function () {
                    const self = this;
                    const args = arguments;

                    if (timerId) {
                        clearTimeout(timerId);
                    }

                    if (immediate) {
                        if (!timerId) {
                            fn.apply(self, args);
                        }
                        timerId = setTimeout(function () {
                            timerId = null;
                        }, wait)
                    } else {
                        timerId = setTimeout(function () {
                            fn.apply(self, args);
                        }, wait);
                    }
                }
            }

            function clg(a, b, c) {
                console.log(a, b, c);
            }

            // 没有加debounce
            document.getElementById('btn_0')
                .addEventListener('click', function (event) {
                    clg(1, 2, 3);
                });

            // 加了debounce,延迟时间内多次点击按钮,只有最后一次触发clg
            const debouncedClg = debounce(clg);
            document.getElementById('btn_1')
                .addEventListener('click', function (event) {
                    debouncedClg(1, 2, 3);
                });

            // 加了debounce,启用immediate,延迟时间内多次点击按钮,只有第一次触发clg
            const debouncedImmediateClg = debounce(clg, 300, true);
            document.getElementById('btn_2')
                .addEventListener('click', function (event) {
                    debouncedImmediateClg(1, 2, 3);
                });
        })();
    </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读