summaryrefslogtreecommitdiff
path: root/graphs/js/throttleDebounce/throttleDebounce.js
diff options
context:
space:
mode:
Diffstat (limited to 'graphs/js/throttleDebounce/throttleDebounce.js')
-rw-r--r--graphs/js/throttleDebounce/throttleDebounce.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/graphs/js/throttleDebounce/throttleDebounce.js b/graphs/js/throttleDebounce/throttleDebounce.js
new file mode 100644
index 0000000..f6e15f9
--- /dev/null
+++ b/graphs/js/throttleDebounce/throttleDebounce.js
@@ -0,0 +1,48 @@
+function debounce(func, n) {
+ let timer = null;
+
+ return (...args) => {
+ clearTimeout(timer);
+ timer = setTimeout(func, n, ...args);
+ };
+}
+function throttle(func, n) {
+ let throttling = false;
+ let last_args = null;
+ let last_call = Date.now();
+ let timeout = null;
+
+ return (...args) => {
+ if (!throttling) {
+ last_call = Date.now();
+ if (last_args) {
+ func.apply(this, last_args);
+ last_args = null;
+ } else {
+ func(...args);
+ }
+
+ throttling = true;
+ if (timeout) {
+ clearTimeout(timeout);
+ }
+
+ timeout = setTimeout(
+ () => {
+ throttling = false;
+
+ if (last_args) {
+ func.apply(this, last_args);
+ }
+ },
+ n - (Date.now() - last_call),
+ );
+ } else {
+ last_args = args;
+ }
+ };
+}
+module.exports = {
+ debounce,
+ throttle,
+};