节流和防抖

节流和防抖

1、节流(throttle)

规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。
代码就是这样的:

		let _lastTime = null;
        // 节流函数,规定时间内只触发一次
        function throttle(fn, gapTime) {
            return (args) => {
                let _nowTime = +new Date();
                if (_nowTime - _lastTime > gapTime || !_lastTime) {
                    fn(args);
                    _lastTime = _nowTime
                }
            }
        }

2、防抖(debounce)

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
代码是这样的:

 // 防抖函数
        let timeout = null;
        // 防抖函数,延迟一段时间后执行函数,如果时间内又触发了那么从新计时
        function debounce(fn, wait) {
            return (args) => {
                if (timeout !== null) {
                    clearTimeout(timeout)
                }
                timeout = setTimeout(() => fn(args), wait)
            }
        }

节流和防抖我放到一起了,大家可以体验一下两者区别

<!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>
<button id="click">防抖</button>
<button id="click1">节流</button>

<body>
    <script>
        // 防抖函数
        let timeout = null;
        // 防抖函数,延迟一段时间后执行函数,如果时间内又触发了那么从新计时
        function debounce(fn, wait) {
            return (args) => {
                if (timeout !== null) {
                    clearTimeout(timeout)
                }
                timeout = setTimeout(() => fn(args), wait)
            }
        }

        function handle(args) {
            console.log(args)
            console.log('处理函数防抖', parseInt((Math.random() * 100)))
        }

        // 节流
        let _lastTime = null;
        // 节流函数,规定时间内只触发一次
        function throttle(fn, gapTime) {
            return (args) => {
                let _nowTime = +new Date();
                if (_nowTime - _lastTime > gapTime || !_lastTime) {
                    fn(args);
                    _lastTime = _nowTime
                }
            }
        }

        function handle1(args) {
            console.log(args)
            console.log('处理函数节流', parseInt((Math.random() * 100)))
        }




        const btn = document.querySelector("#click")

        const btn1 = document.querySelector("#click1")

        btn.addEventListener('click', () => {
            debounce(handle, 1000)({
                id: 'name'
            });
        })

        btn1.addEventListener('click', () => {
            throttle(handle1, 1500)({
                1: 2
            });
        })
    </script>
</body>

</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值