防抖和节流是什么?

防抖和节流是什么?

防抖和节流是频繁触发事件的优化方案

防抖

避免频繁触发,最后一次触发事件后隔n秒后执行

应用场景

输入框搜索、文本框保存、表单提交按钮等等

手写防抖函数

有函数传参时的写法

/**
 * @param {Function} fn
 * @param {number} t milliseconds
 * @return {Function}
 */
var debounce = function (fn, t) {
    let timeId = null
    return function (...args) {
        if (timeId) clearTimeout(timeId)
        timeId = setTimeout(() => fn(...args), t)
    }
};

const log = debounce(console.log, 100)
log('Hello'); // cancelled
log('Hello'); // cancelled
log('Hello'); // Logged at t=100ms

无参写法 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

</head>

<body>
    <input type="text">
    <script>
        const inputDOM = document.querySelector("input")
        let counter = 1;
        function searchChange() {
            console.log(`第${counter++}次请求`);
        }
        inputDOM.oninput = debounce(searchChange, 500)

        // 避免频繁触发,最后一次触发事件后隔n秒后执行
        function debounce(fn, wait) {
            let timer
            return () => {
                if (timer) clearTimeout(timer)
                timer = setTimeout(() => {
                    fn()
                }, wait)
            }

        }
    </script>
</body>

</html>
节流

减少触发事件,每隔n秒后执行

应用场景

scroll事件、拖拽事件、窗口大小调整

手写节流函数
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

</head>

<body>
    <script>
        let counter = 1;
        // 定义处理窗口大小调整的函数
        function handleResize() {
            console.log(`第${counter++}次请求`);
            // console.log('窗口大小已调整:宽度 - ' + window.innerWidth + ', 高度 - ' + window.innerHeight);

        }
        // 添加事件监听器
        window.addEventListener('resize', throttle(handleResize, 500));
        function throttle(fn, wait) {
          
            let timer
            return () => {
                if (timer) return
                timer = setTimeout(() => {
                    timer = null
                    fn()
                }, wait)
            }

        }
    </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值