Skip to content

Instantly share code, notes, and snippets.

@Yawenina
Last active July 15, 2017 08:48
Show Gist options
  • Save Yawenina/88791e6596490f72fcbd45366bde00bf to your computer and use it in GitHub Desktop.
Save Yawenina/88791e6596490f72fcbd45366bde00bf to your computer and use it in GitHub Desktop.
simple debounce and throttle
function debounce(fn, wait, leading = false) {
let timerId,
lastInvokeTime = 0,
context,
args;
const execute = function () {
fn.apply(context, args);
lastInvokeTime = Date.now();
};
return function () {
const now = Date.now();
context = this;
args = arguments;
// clear previous setTimeout invoke
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
// if it is throttle and first call
if (leading && lastInvokeTime === 0) {
// after wait time, invoke it, so it invoked every wait time
timerId = setTimeout(() => {
execute();
}, wait);
// invoke now
return execute();
}
const timeSinceLastInvoke = now - lastInvokeTime;
const diff = wait - timeSinceLastInvoke;
if (diff > 0) {
timerId = setTimeout(() => {
execute();
}, diff);
} else {
// since the lastInvokeTime no longer to be 0, it is the 'first call' after a long time
// so if it is throttle, we should invoke it at once
if (leading) return execute();
// or wait 'wait' time
timerId = setTimeout(() => {
execute();
}, wait);
}
};
}
function throttle(fn, wait) {
return debounce(fn, wait, true);
}
/*
separte function
*/
function separte_debounce(fn, wait) {
let timerId,
context,
args,
lastInvokeTime = 0;
const execute = function () {
fn.apply(context, args);
lastInvokeTime = Date.now();
};
return function () {
const now = Date.now();
context = this;
args = arguments;
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
const timeSinceLastInvoke = now - lastInvokeTime;
const diff = wait - timeSinceLastInvoke < 0 ? wait : wait - timeSinceLastInvoke;
timerId = setTimeout(() => {
execute();
}, diff);
};
}
function separte_throttle(fn, wait) {
let timerId,
lastInvokeTime = 0,
context,
args;
const execute = function () {
fn.apply(context, args);
lastInvokeTime = Date.now();
};
return function () {
context = this;
args = arguments;
const now = Date.now();
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
if (lastInvokeTime) {
const diff = wait - (now - lastInvokeTime);
if (diff > 0) {
timerId = setTimeout(() => {
execute();
}, diff);
} else {
execute();
}
} else {
execute();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment