Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active October 27, 2023 13:51
Show Gist options
  • Save cowboyd/5ae98e35686f96a160ea8105172a3fc7 to your computer and use it in GitHub Desktop.
Save cowboyd/5ae98e35686f96a160ea8105172a3fc7 to your computer and use it in GitHub Desktop.
An Effection operation that takes any operation and runs it periodically on a heart beat
import { action, spawn, sleep, type Operation } from "effection";
export function* heartbeat(duration: number, op: () => Operation<unknown>): Operation<void> {
while (true) {
// this action captures a return point.
yield* action(function* (restart) {
// wait for the duration and return to the next loop iteration
yield* spawn(function*() {
yield* sleep(duration);
restart();
});
// run the operation. If the heartbeat is exceeded, it will be cancelled
yield* op();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment