Skip to content

Commit f6c640b

Browse files
committedJan 30, 2019
feat(js): simplify debounce code
1 parent d8aeee2 commit f6c640b

File tree

1 file changed

+11
-30
lines changed

1 file changed

+11
-30
lines changed
 

‎JS/JS-ch.md

+11-30
Original file line numberDiff line numberDiff line change
@@ -811,39 +811,20 @@ function now() {
811811
* @return {function} 返回客户调用函数
812812
*/
813813
function debounce (func, wait = 50, immediate = true) {
814-
let timer, context, args
815-
816-
// 延迟执行函数
817-
const later = () => setTimeout(() => {
818-
// 延迟函数执行完毕,清空缓存的定时器序号
819-
timer = null
820-
// 延迟执行的情况下,函数会在延迟函数中执行
821-
// 使用到之前缓存的参数和上下文
822-
if (!immediate) {
823-
func.apply(context, args)
824-
context = args = null
825-
}
826-
}, wait)
827-
814+
let timer = 0
815+
// 立即执行时,timeout 回调中不做任何事情
816+
const timeoutFn = immediate ? () => {} : func
828817
// 这里返回的函数是每次实际调用的函数
829818
return function(...params) {
830-
// 如果没有创建延迟执行函数(later),就创建一个
831-
if (!timer) {
832-
timer = later()
833-
// 如果是立即执行,调用函数
834-
// 否则缓存参数和调用上下文
835-
if (immediate) {
836-
func.apply(this, params)
837-
} else {
838-
context = this
839-
args = params
840-
}
841-
// 如果已有延迟执行函数(later),调用的时候清除原来的并重新设定一个
842-
// 这样做延迟函数会重新计时
843-
} else {
844-
clearTimeout(timer)
845-
timer = later()
819+
// 立即执行
820+
if (!timer && immediate) {
821+
func.apply(this, args)
846822
}
823+
clearTimeout(timer)
824+
timer = setTimeout(() => {
825+
timeoutFn.apply(this, args)
826+
timer = 0
827+
}, wait)
847828
}
848829
}
849830
```

0 commit comments

Comments
 (0)
Please sign in to comment.