节流函数

66 阅读1分钟

HTML + JS

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <div id="test" style="width: 300px; height: 300px; background-color: red"></div>
    </body>
    <script>
        function throttle(fun, deely){
            let timer = '';
            return function () {
                if (timer) return;
                timer = setTimeout(() => {
                    fun.call(this, ...arguments);
                    timer = ''
                }, deely);
            };
        };

        let node = document.querySelector('#test');

        node.addEventListener('mousemove',
            throttle(() => {
                console.log(new Date());
            },2000),
        );
    </script>
</html>

效果图

image.png