Last active
February 4, 2016 19:54
-
-
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
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
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