[高频面试题] 节流防抖

一.两者的差别

        节流:  降低事件触发的频率,就是指频繁触发事件,只执行一次。

        防抖:就是指频繁触发事件,只执行最后一次。

二、使用场景

        节流: 鼠标移动mousemove,页面尺寸发生变化resize,滚动条滚动scroll等开销比较大的情况下。

        防抖: 搜索框输入,设定每次输入完毕n秒后发送请求,如果期间还有输入,则重新计算函数执行时间

三.两者的基本实现


        1.节流

let flag = true
document.querySelector(".btn").addEventListener('click', function () {
    if (flag) {
        flag = false
        setTimeout(() => {
            this.style.backgroundColor = 'red'
            flag = true
        }, 2000)
    }
})
ript>

         2.防抖

let timer = null
document.querySelector("input").addEventListener('input', function () {
    clearTimeout(timer)
    timer = setTimeout(() => {
        if (this.value.length >= 6 && this.value.length <= 10) {
            document.querySelector("span").innerHTML = `输入正确`
            document.querySelector("span").style.color = `green`
        } else {
            document.querySelector("span").innerHTML = `输入不符合要求`
            document.querySelector("span").style.color = `red`
        }
    }, 500)
})
ript>

四.两者的封装: 闭包

        1.节流

        定义节流阀

document.querySelector(".btn").addEventListener('click', throttle(function () {
    document.querySelector(".btn").style.backgroundColor = 'red'
}, 2000))

function throttle(cb, t) {
    let flag = true
    return function () {
        if (flag) {
            flag = false
            setTimeout(() => {
                cb()
                flag = true
            }, t)
        }
    }
}

        2.防抖

        每次事件触发的时候都要先判断是否有定时器,如果有就先清除以前的定时器

let input = document.querySelector("input")
input.addEventListener('input', debounce(function () {
    if (input.value.length >= 6 && input.value.length <= 10) {
        document.querySelector("span").innerHTML = `输入正确`
        document.querySelector("span").style.color = `green`
    } else {
        document.querySelector("span").innerHTML = `输入不符合要求`
        document.querySelector("span").style.color = `red`
    }
}, 500))
function debounce(cb, t) {
    let timer = null
    return function () {
        clearTimeout(timer)
        timer = setTimeout(() => {
            cb()
        }, t)
    }
}

五.使用第三方库实现防抖和节流

        1.节流

document.querySelector(".btn").addEventListener('click', _.throttle(function () {
            console.log('haha');
        }, 2000))

        2.防抖

let input = document.querySelector("input")
input.addEventListener('input', _.debounce(function () {
    if (input.value.length >= 6 && input.value.length <= 10) {
        document.querySelector("span").innerHTML = `输入正确`
        document.querySelector("span").style.color = `green`
    } else {
        document.querySelector("span").innerHTML = `输入不符合要求`
        document.querySelector("span").style.color = `red`
    }
}, 500))

你可能感兴趣的:(javascript)