JavaScript 防抖和节流

防抖Debounce

为了防止事件在较短时间内连续触发从而引起对应的事件函数不必要的连续执行的事件处理机制。

一旦开始触发事件,Throttle保证了每个时间段内事件函数至少执行一次,Debounce则没有这样的保证。

防抖 debounce

在一定时间间隔内,事件函数被触发多次,但只执行最后一次。

防抖就像坐电梯,如果在关门的时候你一直按开门键,那么门会一直打开。门只会在你最后一次按下的时间间隔后关闭。

常见场景:

浏览器窗口调整,只在最后调整完成后才进行resize

电商网站的导航、搜索网站的输入提示等等

    <button onclick="clickMe(1)">click me</button>
    <script>
        const clickMe = debounce((a) => {
            console.log(a);
        }, 500)
        function debounce(fn, timeout) {
            let timer = null
            return function () {
                let context = this
                let args = Array.prototype.slice.call(arguments)
                if (timer) {
                    clearTimeout(timer)
                    timer = null
                }
                timer = setTimeout(() => {
                    fn.apply(context,args)
                }, timeout);
            }
        }
    </script>

节流  throttle

不管事件函数触发多少次,只在经过一定时间间隔后才会执行一次。节流会稀释函数的执行频率。

节流就像闹钟,不管表针转动几次,在恒定的周期里它只叫响一次。

常见场景: 登录页面判断文本框录入并给出提示信息

    <button onclick="clickMe(1)">click me</button>
    <script>
        const clickMe = throttle((a) => {
            console.log(a)
        }, 2000)
        function throttle(fn, delay) {
            let timer = null
            return function () {
                if (timer) return
                const args = Array.from(arguments)
                timer = setTimeout(() => {
                    fn.apply(this, args)
                    clearTimeout(timer)
                    timer = null
                }, delay);
            }
        }
    </script>
posted @ 2020-02-21 21:00  IslandZzzz  阅读(197)  评论(0编辑  收藏  举报