js中防抖 debounce 节流 throttle 原理 从0手动实现

1 防抖

        高频触发事件时,执行损耗高的操作,连续触发过程中,只执行最后一次

  1. 高频事件:input scroll resize等。
  2. 损耗高:网络请求、dom操作。

         实现防抖步骤:1.在回调函数中判断timer是否存在,存在就清理计时器,重新计时执行。2.在实现debounce函数时,注意返回函数和传入的函数参数都不能时回调函数,否在造成this丢失。3. debounce函数中返回函数顶层使用this保存,回调函数使用apply调用。 4.要使传递参数可行,顶层函数解构赋值参数,然后再回调apply时传入参数(注意不需要解构,...args时就是个数组)。

// 防抖: 防止js函数在短时间内被频繁调用,减少性能消耗以及视觉抖动或者网络消耗服务器资源
// 防抖原理:再触发频率高的事件中,执行耗费性能的操作,连续操作后,只有最后一次操作生效
// 频率高的事件:resize, input, scroll, mousemove, mouseover, mouseout, keyup, keydown, keypress
// 耗费性能的操作:dom操作,网络请求

// 事件触发后,延迟一段时间执行函数,如果在这段时间内再次触发事件,则重新计时
let timer = null
document.getElementById('btn').addEventListener('click' , ()=>{
    timer && clearTimeout(timer)
    timer = setTimeout(()=>{
        console.log('click__debounce')
    }, 500)
})

// 也可以使用lodash库中的debounce方法,lodash(func, [wait=0], [options={}])
class _ {
    static debounce(callback, wait){
        let timer = null
        // 返回不能使用箭头函数,否则无法获取this中的dom元素
        return function(...args){
            // 存储调用时的this(一般是dom元素)
            const _this = this
            timer && clearTimeout(timer)
            timer = setTimeout(()=>{
                // 通过apply将this指向调用时的dom元素
                callback.apply(_this, args)
            }, wait)
        }
    }
}

// 传入函数不能使用箭头函数,否则无法绑定this
const debounceFunc = _.debounce(function(e){
    console.log(e)
    console.log(this)
    console.log('input')
}, 500)

document.querySelector('input').addEventListener('input', debounceFunc)

2 节流

        高频触发事件时,执行损耗高的操作,连续触发过程中,在设置好的单位时间内只执行一次

        流程和防抖类似,区别在于每次判断定时器是否存在,如果存在就不执行任何操作,如果定时器不存在,那么需要重新设置定时器,并且再定时器的回调函数内部执行末尾清除定时器。代码如下所示:

// 节流: 频繁触发事件时,减少触发次数,提高性能
// 例如:视频播放时 保存播放进度
// 防抖原理:再触发频率高的事件中,执行耗费性能的操作,连续操作后,单位事件内只有一次生效
// lodash库中的throttle方法,lodash(func, [wait=0], [options={}])
let timer_t = undefined
document.getElementById('btn_t').addEventListener('click', () => {
    if(!timer_t){
        timer_t = setTimeout(()=>{
            console.log('click throttle')
            timer_t = undefined
        }, 1000)
    }
})


_.throttle = function(callback, wait){
    let timer = undefined
    return function(...args){
        _this = this
        if(!timer){
            timer = setTimeout(()=>{
                callback.apply(_this, args)
                timer = undefined
            }, 1000)
        }
    }
}

const throttleFunc = _.throttle(function(e){
    console.log(this)
    console.log(e)
    console.log("click throttle")
})


document.getElementById('input_t').addEventListener('input', throttleFunc)

3 配套文件index.html

        新建index.js将上述代码拷贝即可在控制台查看效果,index.html内容如下:

<!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>
<div>
    <button id="btn">click_debounce</button>
    <button id="btn_t">click_throttle</button>
    <input type="text" id="input">
    <input type="text" id="input_t">
    <script src="08_index.js"></script>
</div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值