May 09, 2021 CoffeeScript
You want to execute a function only once, and combine multiple consecutive calls at the beginning or end into a simple operation.
Use a named function:
debounce: (func, threshold, execAsap) ->
timeout = null
(args...) ->
obj = this
delayed = ->
func.apply(obj, args) unless execAsap
timeout = null
if timeout
clearTimeout(timeout)
else if (execAsap)
func.apply(obj, args)
timeout = setTimeout delayed, threshold || 100
mouseMoveHandler: (e) ->
@debounce((e) ->
# 只能在鼠标光标停止 300 毫秒后操作一次。
300)
someOtherHandler: (e) ->
@debounce((e) ->
# 只能在初次执行 250 毫秒后操作一次。
250, true)
See John Hann's blog post to learn about JavaScript's way to shake.