API reference › @evolu/common › Task › repeat
function repeat<T, E, D, Output>(
task: Task<T, E, D>,
schedule: Schedule<Output, T>,
__namedParameters?: RepeatOptions<T, Output>,
): Task<T, E, D>;
Defined in: packages/common/src/Task.ts:4159
Repeats a Task according to a Schedule.
Runs the Task once, then repeats while the Task returns Ok, the
schedule yields another delay, and RepeatOptions.shouldRepeat returns
true. When repeating stops, repeat returns the last successful
Result. If the Task returns Err, including Done from a
NextTask, repeat returns that error without scheduling another
attempt.
Use repeat for success-driven loops such as polling or consuming a
NextTask: it repeats after Ok and returns the Task's natural Result. Use
retry for failure recovery: it repeats after Err and wraps the final
domain error in RetryError.
With take(n), the Task runs n+1 times: the initial attempt plus n repeats.
Repeating successes
import {
assertEqual,
assertOk,
createRun,
ok,
recurs,
repeat,
type Task,
} from "@evolu/common";
let attempts = 0;
const checkStatus: Task<string> = () => {
attempts += 1;
return ok("pending");
};
const poll = repeat(checkStatus, recurs(3));
await using run = createRun();
assertOk(await run(poll), "pending");
assertEqual(attempts, 4);
Stopping with Done
import {
assertErr,
assertEqual,
createRun,
done,
err,
ok,
repeat,
spaced,
type NextTask,
} from "@evolu/common";
interface Item {
readonly id: string;
}
const queue: Array<Item> = [{ id: "item-1" }];
const processQueue: NextTask<Item> = () => {
const item = queue.shift();
return item ? ok(item) : err(done());
};
await using run = createRun();
const result = await run(repeat(processQueue, spaced("1ms")));
assertErr(result, done());
assertEqual(queue, []);