美文网首页
[JavaScript] 防抖函数debounce的实现及其应用

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

作者: jiansheng | 来源:发表于2019-03-05 17:49 被阅读0次
    <!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>
    

    相关文章

      网友评论

          本文标题:[JavaScript] 防抖函数debounce的实现及其应用

          本文链接:https://www.haomeiwen.com/subject/adyouqtx.html