Last active
August 29, 2015 14:09
-
-
Save chenwery/f56e60df30c7394a3ad0 to your computer and use it in GitHub Desktop.
throttle AND debounce
This file contains 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
var throttle = function (fn,delay, immediate, debounce) { | |
var curr = +new Date(),//当前事件 | |
last_call = 0, | |
last_exec = 0, | |
timer = null, | |
diff, //时间差 | |
context,//上下文 | |
args, | |
exec = function () { | |
last_exec = curr; | |
fn.apply(context, args); | |
}; | |
return function () { | |
curr= +new Date(); | |
context = this, | |
args = arguments, | |
diff = curr - (debounce ? last_call : last_exec) - delay; | |
clearTimeout(timer); | |
if (debounce) { | |
if (immediate) { | |
timer = setTimeout(exec, delay); | |
} else if (diff >= 0) { | |
exec(); | |
} | |
} else { | |
if (diff >= 0) { | |
exec(); | |
} else if (immediate) { | |
timer = setTimeout(exec, -diff); | |
} | |
} | |
last_call = curr; | |
} | |
}; | |
var debounce = function (fn, delay, immediate) { | |
return throttle(fn, delay, immediate, true); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment