美文网首页
防抖函数与节流函数

防抖函数与节流函数

作者: 我没叫阿 | 来源:发表于2023-06-14 09:29 被阅读0次

防抖(debounce)

  • 定义: 用户触发事件过于频繁,只执行最后一次事件的操作。如果用户在设置时间内又触发此事件,则重新计算时长。
  • 参数1:需要执行的函数
  • 参数2:需要延迟的时间
        function debounce(fn, delay) {
            // 定义一个定时器
            let timer = null

            return function () {
                // 取消上一次的定时器
                if (timer) clearTimeout(timer)
                // 延迟多少秒执行传进来的函数方法
                timer = setTimeout(() => {
                    fn()
                }, delay)
            }
        }

        let input = document.getElementById('input')
        input.addEventListener('input', debounce(changeValue, 2000))

        function changeValue() {
            console.log('改变输入框');
        }

节流(throttle)

  • 定义: 事件触发事件过于频繁,控制执行次数。
  • 参数1:需要执行的函数
  • 参数2:需要延迟的时间
        function throttle(fn, delay) {
            // 定义一个定时器
            let timer = null

            return function () {
                if (!timer) {
                    timer = setTimeout(() => {
                        fn()
                        timer = null
                    }, delay)
                }
            }
        }

        let box = document.getElementById('box')
        box.addEventListener('touchmove',throttle(moveBox,2000))

        function moveBox() {
            console.log('移动了');
        }

相关文章

网友评论

      本文标题:防抖函数与节流函数

      本文链接:https://www.haomeiwen.com/subject/dfihydtx.html