今天晚上听了函数防抖与节流,记录一下。
防抖(debounce)
- 如果下达该命令后,在t毫秒内再次下达该命令,则取消刚刚下达的命令,只执行新命令
- 最终效果: 对于连续动作(动作间的时间间隔小于t),以最后一次为准
代码如下:
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
网友评论