Skip to content

Commit

Permalink
debounce sync and save -- only run them every 100ms
Browse files Browse the repository at this point in the history
  • Loading branch information
pvh committed Oct 14, 2023
1 parent 10672a3 commit 4e726dd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/automerge-repo/src/Repo.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
25 changes: 25 additions & 0 deletions packages/automerge-repo/src/helpers/debounce.ts
Original file line number Diff line number Diff line change
@@ -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 = <F extends (...args: Parameters<F>) => ReturnType<F>>(
fn: F,
rate: number
) => {
let timeout: ReturnType<typeof setTimeout>
return function (...args: Parameters<F>) {
clearTimeout(timeout)
timeout = setTimeout(() => {
fn.apply(null, args)
}, rate)
}
}

0 comments on commit 4e726dd

Please sign in to comment.