美文网首页
[JavaScript] 节流函数throttle的实现及其应用

[JavaScript] 节流函数throttle的实现及其应用

作者: jiansheng | 来源:发表于2019-03-06 18:54 被阅读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>throttle</title>
</head>

<body>
    <button id="btn_0">simple button</button>
    <button id="btn_1">throttle button</button>
    <script>
        (function () {
            function throttle(fn, interval = 500) {
                let timerId = null;
                let previousTime = 0;

                return function () {
                    const self = this;
                    const args = arguments;
                    const now = Date.now();
                    const diffTime = now - previousTime;
                    if (diffTime >= interval) {
                        if (!timerId) {
                            previousTime = now;
                            fn.apply(self, args);
                            timerId = setTimeout(() => {
                                timerId = null;
                            }, interval);
                        }
                    }
                }
            }

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

            document.getElementById('btn_0')
                .addEventListener('click', function (event) {
                    clg(1, 2, 3);
                });

            const throttledClg = throttle(clg);
            document.getElementById('btn_1')
                .addEventListener('click', function (event) {
                    throttledClg(1, 2, 3);
                });

        })();
    </script>
</body>

</html>

相关文章

网友评论

      本文标题:[JavaScript] 节流函数throttle的实现及其应用

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