Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ianmetcalf
Last active February 4, 2016 19:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianmetcalf/36bfd0ab74b2bb5804a3 to your computer and use it in GitHub Desktop.
Save ianmetcalf/36bfd0ab74b2bb5804a3 to your computer and use it in GitHub Desktop.
Delay redraw for debounced events,based on https://www.npmjs.com/package/debounce
import m from 'mithril';
import now from 'date-now';
export default function debounce(func, wait = 100, immediate = false) {
let context, args, timestamp, timeout, result;
function debounced() {
context = this;
args = arguments;
timestamp = now();
if (!timeout) {
m.startComputation();
timeout = setTimeout(later, wait);
if (immediate) {
result = func.apply(context, args);
context = args = null;
}
}
return result;
}
function later() {
const elapsed = now() - timestamp;
if (elapsed < wait && elapsed > 0) {
timeout = setTimeout(later, wait - elapsed);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
m.endComputation();
}
}
return debounced;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment