Skip to content

Task Queue

Queuing

TaskQueueMutable is a utility class to run a series of functions one-by-one.

import { TaskQueueMutable, sleep } from "https://unpkg.com/ixfx/dist/flow.js"
// Get the shared task queue
const q = TaskQueueMutable.shared;
// After that, add a task whenever you like
q.enqueue(async () => {
// Do something...
// Wait one second before allowing the next task to run
await sleep(1000);
});

‘Tasks’ are just async functions. The queue waits for the function to return a result, after which it takes the next item in the queue to process.

It’s also possible to listen for when the queue has started processing some events and when it has finished, with the ‘started’ and ‘empty’ events.

Calling with a timeout

There are times you might want to call a function, but handle cases where it fails or we don’t get a result after some period. Flow.waitFor helps with this.

The signature is:

function waitFor(
timeoutMs: number,
onAborted: (reason: string) => void,
onComplete?: (success: boolean) => void
):(error:message) => void

Flow.waitFor returns a function for signalling the result. If this function is not called within the timeout, or is passed an error message, the abort callback will run.

// Set up waitFor, with a timeout of 1 second
// If an error occurs, we just print it out
const done = waitFor(1000, (error) => {
console.error(error);
});
// Mark as done when user clicks
document.addEventListener(`click`, () => {
done();
});
// Mark as failed if person presses a key
document.addEventListner(`keypress`, () => {
done(`Ooops, key was pressed`);
});

In the above example, we only listen for the error case - if the timeout happens or the user presses a key. We can also get notified when the operation completes, successfully or not.

const done = waitFor(1000,
(error) => {
console.error(error);
},
(success) => {
if (!success) return; // Failed
console.log(`yay`);
}
);