Last active
October 27, 2023 13:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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