js Debounce Throttle 手写防抖与节流

手写防抖

  1. 如果存在之前的计时器,取消重新计时。 即多次点击只执行最后一次
  2. 注意this指向和回调形参列表
    <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>

手写节流

  1. 只在固定的一段时间之后执行
  2. 在定时器回调里清除timer,如果当前已经有timer了,直接return, 实现一段时间内只执行一次
    <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 @ 2022-06-14 16:23  IslandZzzz  阅读(40)  评论(0编辑  收藏  举报