debounce 去抖

我的理解很简单,比方说window.onscroll会疯狂触发handler,此时给它一个debounce(handler, delayTime).

就是不管你延时时间内触发了多少hanlder,我最后只执行一次。(理解把之前多次触发合并成一次,节省浏览器工作)

function debounce(fn, delay) {
var ctx
var args
var timer = null
var later = function () {
fn.apply(ctx, args)
timer = null
}
return function () {
ctx = this
args = arguments
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(later, delay)
}
}

throttle 节流

不管你怎么触发#24,反正我就是固定时间内必定触发一次

function throttle(fn, delay) {
var ctx
var args
var previous = Date.now()
var later = function () {
fn.apply(ctx, args)
}
return function () {
ctx = this
args = arguments
var now = Date.now()
var diff = now - previous - delay
if (diff >= 0) {
previous = now
setTimeout(later, delay)
}
}
}

以上参考地址:https://segmentfault.com/a/1190000005926579

我在想 throttle可以这样改吗。。。

function throttle(fn, delay) {
var ctx
var args
var timer = null
var later = function () {
fn.apply(ctx, args)
timer = null
}
return function () {
ctx = this
args = arguments
if (timer) return
timer = setTimeout(later, delay)
}
}

哈哈这段我没测试鸭(懒癌)。错了请告诉我我删掉

05-11 22:00