Skip to content

Instantly share code, notes, and snippets.

@userkang
Last active January 14, 2019 10:10
Show Gist options
  • Save userkang/cc3f68bc2626c4c3290d3554feda3a32 to your computer and use it in GitHub Desktop.
Save userkang/cc3f68bc2626c4c3290d3554feda3a32 to your computer and use it in GitHub Desktop.
节流函数
function throttle(func, wait, options) {
var timeout, context, args
var previous = 0
if (!options) options = {}
var later = function() {
previous = options.leading === false ? 0 : Date.now()
timeout = null
func.apply(context, args)
if (!timeout) context = args = null
}
var thorttled = function() {
var now = Date.now()
if (!previous && options.leading === false) previous = now
var remaining = wait - (now - previous)
context = this
args = arguments
// 如果没有剩余的时间了或者你改了系统时间
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
func.apply(context, args)
if (!timeout) context = args = null
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, wait)
console.log(2)
}
}
return thorttled
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment