Last active
January 14, 2019 10:10
-
-
Save userkang/cc3f68bc2626c4c3290d3554feda3a32 to your computer and use it in GitHub Desktop.
节流函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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