防抖函数和节流函数

本文展示了如何使用JavaScript实现防抖(debounce)和节流(throttle)函数,以优化频繁触发的事件处理,如输入框输入时的网络请求。防抖函数通过限制函数的执行频率,确保在一定延迟后才执行;节流函数则保证在固定间隔内执行。同时,防抖函数还实现了取消功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.防抖功能实现(包含取消功能实现)

<!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>
    <input type="text">
    <button class="cancel">取消</button>
    <script>
        /**
        * 防抖函数:实现防抖以及取消功能
        * @param fn 回调函数
        * @param delay 延迟时间
        */
        function wqdebounce(fn, delay) {
            // 1.用于记录上一次事件触发的timer
            let timer = null
            // 2.触发事件时执行的函数
            const _debounce = function (...args) {
                // 2.1如果有再次触发(更多次触发)事件,那么取消上一次的事件
                if (timer) clearTimeout(timer)
                // 2.2延迟去执行对应的fn函数(传入的回调函数)
                timer = setTimeout(() => {
                    fn.apply(this, args)
                    timer = null // 执行过函数之后,将timer重新置null
                }, delay);
            }

            // 3.给_debounce绑定一个取消的函数
            _debounce.cancel = function () {
                if (timer) clearTimeout(timer)
                timer = null
            }
            // 返回一个新的函数
            return _debounce
        }

        // 获取input元素
        const inputEl = document.querySelector('input')
        // 获取button元素
        const cancelBtn = document.querySelector('.cancel')

        // 实现防抖
        let counter = 1
        const debounceFn = wqdebounce(function (event) {
            console.log(`发送网络请求${counter++}:`, this, event);
        }, 2000)
        inputEl.oninput = debounceFn

        // 实现取消的功能
        cancelBtn.onclick = function () {
            debounceFn.cancel()
        }
    </script>
</body>

</html>

2.节流功能实现

<!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>
    <input type="text">
    <script>
        /**
        * 节流函数:实现节流功能
        * @param fn 回调函数
        * @param interval 间隔时间
        */
        function wqthrottle(fn, interval) {
            // 1.用于记录上一次事件触发的时间
            let lastTime = 0
            // 2.触发事件时执行的函数
            const _throttle = function (...args) {
                // 2.1获取当前时间
                const nowTime = new Date().getTime()
                // 2.2如果当前时间减去上次时间大于间隔时间,执行回调函数
                if (nowTime - lastTime > interval) {
                    fn.apply(this, args)
                    lastTime = nowTime
                }
            }

            return _throttle
        }

        // 获取input元素
        const inputEl = document.querySelector('input')
        // 实现节流
        let counter = 1
        inputEl.oninput = wqthrottle(function (event) {
            console.log(`发送网络请求${counter++}:`, this.value, event);
        }, 2000)

    </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值