]> git.wincent.com - hextrapolate.git/commitdiff
Add simple debounce module
authorGreg Hurrell <greg@hurrell.net>
Tue, 4 Aug 2015 06:18:42 +0000 (23:18 -0700)
committerGreg Hurrell <greg@hurrell.net>
Tue, 4 Aug 2015 06:18:42 +0000 (23:18 -0700)
Copy-pasta'd from:

https://github.com/wincent/corpus/blob/a41b05e0a38f5bdb4c630c206780cae0db91dbea/src/app/debounce.js

src/debounce.js [new file with mode: 0644]

diff --git a/src/debounce.js b/src/debounce.js
new file mode 100644 (file)
index 0000000..4a5145b
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * Copyright 2015-present Greg Hurrell. All rights reserved.
+ * Licensed under the terms of the MIT license.
+ *
+ * @flow
+ */
+
+'use strict';
+
+/**
+ * Debounce implementation that fires on the trailing edge only. If a call comes
+ * in when a pending call is yet to be finalized, it replaces the pending call.
+ */
+export default function debounce(fn, interval) {
+  let timeout = null;
+  return function() {
+    const args = arguments;
+    const context = this;
+    clearTimeout(timeout);
+    timeout = setTimeout(() => fn.apply(context, args), interval);
+  };
+}