什么是防抖和节流,JS如何编码实现?

防抖 (debounce) 函式是指,将多次操作优化为,只在最后一次执行。具体来说,当一定时间内没有持续触发事件时,事件处理函式才会被执行一次,但如果在设定的时间内又一次触发了事件,就会重新开始计时。

function debounce(func, wait) {
    let timeout;

    return function () {
        let context = this; // 保存this指向
        let args = arguments; // 拿到event对象

        clearTimeout(timeout)
        timeout = setTimeout(function(){
            func.apply(context, args)
        }, wait);
    }
}

节流 (throttle) 指的是,在一段时间内只会执行一次触发事件的回调 (callback) 函式,若在这之中又有新事件触发,则不执行此回调函式。

function throttled1(fn, delay = 500) {
    let oldtime = Date.now()
    return function (...args) {
        let newtime = Date.now()
        if (newtime - oldtime >= delay) {
            fn.apply(null, args)
            oldtime = Date.now()
        }
    }
}

 

原创文章,作者:czhdawn,如若转载,请注明出处:https://www.czhdawn.cn/archives/4952

(0)
czhdawn的头像czhdawn
上一篇 3天前
下一篇 14小时前

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注