防抖和节流

92 阅读1分钟

防抖函数

当持续触发事件,一定时间没有再触发事件,事件处理才会执行一次,如果设定时间到来之前,又被触发事件,则重新开始计时

// 封装防抖函数
function debounce (delay, callback) {
    let timer = null;
    return function (value) {
        timer = setTime( () => {
            callback(value)
        }, delay)
    }
}

function fn (value) {
    // 事件返回结果
    console.log(value)
}

var debounceFun = debounce(1000,fn)

input.addEventListener('keyup', function (e) {
    debounceFun(e.target.value) // 触发事件
})

实际应用

1、改变浏览器宽度,重新渲染

2、连续输入后结束返回搜索结果

3、登录解决多次点击

节流

当持续触发函数,保证一段时间内,只调用一次事件处理函数

function throttle (delay, fn) {
    let timer = null;
    return function () {
        if(!timer) {
            setTimeout(() => {
                fn()
                timer = null;
            }, delay)
        }
    }
}

function handle () {
    console.log(Math.random())
}

document.getElementById('button').onclick = throttle(1000,handle)

实际使用

1、图片懒加载

2、实时数据节流

知识点

1、闭包:函数中 return 函数

2、Math.random() 随机数