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

2019-03-06  本文已影响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>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>
上一篇下一篇

猜你喜欢

热点阅读