Files
factorio-clusterio/packages/web_ui/src/util/exclusive.ts
T
2026-10-27 21:32:51 +00:00

26 lines
615 B
TypeScript

/** Runs one task at a time, refusing tasks started while another is running */
export class ExclusiveRunner<State> {
current?: State;
onChange: (state?: State) => void;
constructor(onChange: (state?: State) => void) {
this.onChange = onChange;
}
/** Run the task unless another is running, returns false if it was refused */
async run(state: State, task: () => Promise<void>) {
if (this.current !== undefined) {
return false;
}
this.current = state;
this.onChange(state);
try {
await task();
} finally {
this.current = undefined;
this.onChange(undefined);
}
return true;
}
}