美文网首页
js防抖 节流

js防抖 节流

作者: 事在人为s | 来源:发表于2020-04-15 16:38 被阅读0次

防抖

function debounce(fn, delay = 500) {
    // timer 是闭包中的
    let timer = null

    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}
//使用
let input1 = document.getElementById('input1')
input1.addEventListener('keyup', debounce(function (e) {
    console.log(e.target)
    console.log(input1.value)
}, 600))

节流

function throttle(fn, delay = 100) {
    let timer = null

    return function () {
        if (timer) {
            return
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}

相关文章

网友评论

      本文标题:js防抖 节流

      本文链接:https://www.haomeiwen.com/subject/rkacvhtx.html