防抖(Debounce)是指在肯定工夫内,当函数被频繁触发时,只有在最初一次触发后的延迟时间内,函数才会被真正执行。如果在延迟时间内又有触发事件产生,会从新开始计时。

简洁的讲就是:n秒后执行该事件,在n秒内被反复触发,则从新计时。

代码实现:

<!DOCTYPE html><html><head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1">    <title></title>    <style>        #btn {            width: 100px;            height: 40px;            margin: 40px;            background-color: aqua;            cursor: pointer;            border: solid 2px #000;            border-radius: 5px;        }    </style></head><body>    <div>        <button type="button" id="btn">点击我</button>    </div>    <script type="text/javascript">        //获取 按钮        let btn = document.querySelector('#btn');        // “点击我”的办法        function palyClick() {            // console.log(this);            console.log('哈哈哈,我被你点击了');        }        // 封装防抖函数        // func: 点击按钮要执行的函数        // delay: 延迟时间        function debounce(func, delay) {            // 设置定时器标识            let timer = null;            //留神这里不能应用箭头函数 否则会扭转this的指向            return function () {                let _this = this;                // 革除 timer 延时办法                if (timer !== null) {                    // 革除定时器                    clearTimeout(timer);                }                //设置定时器                timer = setTimeout(() => {                    func.apply(_this);                    timer = null;                }, delay)            }        }        // 给按钮增加d点击事件监听 点击时,执行debounce函数,延时工夫为1000         btn.addEventListener('click', debounce(palyClick, 2000));    </script></body></html>

成果视频:

节流(Throttle)是指在肯定工夫内,无论函数被触发多少次,函数只会在固定的工夫距离内执行一次。如果在工夫距离内有屡次触发事件,只会执行最初一次。

简洁的讲就是:n秒内只运行一次,在n秒内反复被触发,只有最初一次是失效。

代码实现:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title>    <style>        #btn {            width: 100px;            height: 40px;            margin: 40px;            cursor: pointer;        }    </style></head><body>    <button id="btn">触发按钮</button>    <script>        //获取 按钮        const btn = document.getElementById("btn");        // “触发按钮”的办法        function playClick() {            console.log("节流办法曾经触发");        }        // 封装节流函数        function Throttle(Fun, time) {            let flag = false            return function () {                //首次执行办法,flag置为true                if (!flag) {                    Fun();                    flag = true;                }                //当定时器中回调函数执行完,将flag置为false时,才会从新执行办法语句                setTimeout(() => {                    flag = false;                }, time)            }        };        btn.onclick = Throttle(playClick, 3000);    </script></body></html>

成果视频: