函数防抖和节流

2019-05-15  本文已影响0人  弹指一挥间_e5a3

今天晚上听了函数防抖与节流,记录一下。

防抖(debounce)


代码如下:

function debounce(fn, wait) {
    let timer = null
    return function() {
        if(timer) 
            clearTimeout(timer)
        timer = setTimeout(() => fn.apply(this, arguments), wait)
    }
}

let fn = () => console.log('这里只执行很少次')
fn = debounce(fn, 1000)

document.body.onscroll = fn

节流(throttle)

function throttle(fn, gapTime) {
    let lastTime = null
    let nowTime = null
    return function() {
        nowTime = Date.now()
        if(!lastTime || nowTime - lastTime > gapTime) {
            fn()
            lastTime = nowTime
        }
    }
}

let fn = () => console.log('我执行了')
fn = throttle(fn, 1000)

document.body.onscroll = fn

范例如下:
输入文字,用防抖与节流分别对其进行保存。
http://js.jirengu.com/bucularili/1/edit?html,js,output

上一篇下一篇

猜你喜欢

热点阅读