Skip to content

Instantly share code, notes, and snippets.

@chenwery
Last active August 29, 2015 14:09
Show Gist options
  • Save chenwery/f56e60df30c7394a3ad0 to your computer and use it in GitHub Desktop.
Save chenwery/f56e60df30c7394a3ad0 to your computer and use it in GitHub Desktop.
throttle AND debounce
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