From 4e726dd04f982438be6998df22c69b9f3b49c881 Mon Sep 17 00:00:00 2001 From: Peter van Hardenberg Date: Fri, 13 Oct 2023 16:57:13 -0700 Subject: [PATCH] debounce sync and save -- only run them every 100ms --- packages/automerge-repo/src/Repo.ts | 2 +- .../automerge-repo/src/helpers/debounce.ts | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 packages/automerge-repo/src/helpers/debounce.ts diff --git a/packages/automerge-repo/src/Repo.ts b/packages/automerge-repo/src/Repo.ts index aa7859e1d..ede0bdd65 100644 --- a/packages/automerge-repo/src/Repo.ts +++ b/packages/automerge-repo/src/Repo.ts @@ -1,7 +1,7 @@ import { next as Automerge } from "@automerge/automerge" import debug from "debug" import { EventEmitter } from "eventemitter3" -import { DocHandle } from "./DocHandle.js" +import { DocHandle, DocHandleEncodedChangePayload } from "./DocHandle.js" import { generateAutomergeUrl, isValidAutomergeUrl, diff --git a/packages/automerge-repo/src/helpers/debounce.ts b/packages/automerge-repo/src/helpers/debounce.ts new file mode 100644 index 000000000..70614c7a4 --- /dev/null +++ b/packages/automerge-repo/src/helpers/debounce.ts @@ -0,0 +1,25 @@ +/** throttle( callback, rate ) + * Returns a throttle function with a build in debounce timer that runs after `wait` ms. + * + * Note that the args go inside the parameter and you should be careful not to + * recreate the function on each usage. (In React, see useMemo().) + * + * + * Example usage: + * const callback = throttle((ev) => { doSomethingExpensiveOrOccasional() }, 100) + * target.addEventListener('frequent-event', callback); + * + */ + +export const throttle = ) => ReturnType>( + fn: F, + rate: number +) => { + let timeout: ReturnType + return function (...args: Parameters) { + clearTimeout(timeout) + timeout = setTimeout(() => { + fn.apply(null, args) + }, rate) + } +}