// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import { delay } from "./delay.ts";
/** Error thrown when {@linkcode Deadline} times out. */ export class DeadlineError extends Error {
  /**
   * Constructs a new {@linkcode DeadlineError} instance.
   *
   * @example
   * ```
   * import { DeadlineError } from "https://deno.land/std@$STD_VERSION/async/deadline.ts";
   *
   * throw new DeadlineError();
   * ```
   */ constructor(){
    super("Deadline");
    this.name = this.constructor.name;
  }
}
/**
 * Create a promise which will be rejected with {@linkcode DeadlineError} when
 * a given delay is exceeded.
 *
 * Note: Prefer to use {@linkcode AbortSignal.timeout} instead for the APIs
 * that accept {@linkcode AbortSignal}.
 *
 * @example
 * ```ts
 * import { deadline } from "https://deno.land/std@$STD_VERSION/async/deadline.ts";
 * import { delay } from "https://deno.land/std@$STD_VERSION/async/delay.ts";
 *
 * const delayedPromise = delay(1000);
 * // Below throws `DeadlineError` after 10 ms
 * const result = await deadline(delayedPromise, 10);
 * ```
 */ export function deadline(p, ms, options = {}) {
  const controller = new AbortController();
  const { signal } = options;
  if (signal?.aborted) {
    return Promise.reject(new DeadlineError());
  }
  signal?.addEventListener("abort", ()=>controller.abort(signal.reason));
  const d = delay(ms, {
    signal: controller.signal
  }).catch(()=>{}) // Do NOTHING on abort.
  .then(()=>Promise.reject(new DeadlineError()));
  return Promise.race([
    p.finally(()=>controller.abort()),
    d
  ]);
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImh0dHBzOi8vZGVuby5sYW5kL3N0ZEAwLjIxNy4wL2FzeW5jL2RlYWRsaW5lLnRzIl0sInNvdXJjZXNDb250ZW50IjpbIi8vIENvcHlyaWdodCAyMDE4LTIwMjQgdGhlIERlbm8gYXV0aG9ycy4gQWxsIHJpZ2h0cyByZXNlcnZlZC4gTUlUIGxpY2Vuc2UuXG4vLyBUaGlzIG1vZHVsZSBpcyBicm93c2VyIGNvbXBhdGlibGUuXG5cbmltcG9ydCB7IGRlbGF5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