Delay
Flow.delay runs a function after some specified delay.
In the below example, someFn will be run after 100 milliseconds. Execution continues immediately after the call to delay, so “B” will be logged first, and then “A” will be logged after 100 milliseconds.
const someFn = () => console.log(`A`);delay(someFn, 100);console.log(`B`);To wait for the scheduled function to run, use await. In this case, you’d see “A” logged before “B”:
const someFn = () => console.log(`A`);await delay(someFn, 100);console.log(`B`);If the interval given is a number, it’s assumed to be milliseconds, but you can also provide an an ixfx Interval type:
await delay(someFn, { secs: 10 }); // Wait 10 secondsawait delay(someFn, { mins: 10 }); // Wait 10 minutesIn the default case, the waiting period is before the callback is run. But you can also specify whether to apply the waiting period after the callback, or both before and after:
// Triggers `someFn` immediately, and then waits 10 seconds before continuingawait delay(someFn, { delay: "after", secs: 10 });
// We wait for 10s, run `someFn`, wait another 10s and then continuingawait delay(someFn, { delay: "both", secs: 10 });
// This is the default case: wait happens before the callback is runawait delay(someFn, { delay: "before", secs: 10 });Compared to ‘sleep’
Section titled “Compared to ‘sleep’”If you don’t want to trigger a function, just want to pausing execution, consider using Flow.sleep instead.
So instead of writing:
import { sleep } from "https://unpkg.com/ixfx/dist/flow.js"await sleep(100); // Pause for 100msawait someFn(); // Call and wait for someFn to runYou can write:
import { delay } from "https://unpkg.com/ixfx/dist/flow.js"await delay(someFn, 100);sleep is particularly succinct when you have multiple sleeps between code:
await doSomething();await sleep(100);await doSomethingElse();await sleep(50);await andAnotherThing();