// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/**
 * A debounced function that will be delayed by a given `wait`
 * time in milliseconds. If the method is called again before
 * the timeout expires, the previous call will be aborted.
 */ /**
 * Creates a debounced function that delays the given `func`
 * by a given `wait` time in milliseconds. If the method is called
 * again before the timeout expires, the previous call will be
 * aborted.
 *
 * @example
 * ```
 * import { debounce } from "https://deno.land/std@$STD_VERSION/async/debounce.ts";
 *
 * await Array.fromAsync(
 *   Deno.watchFs('./'),
 *   debounce((event) => {
 *     console.log('[%s] %s', event.kind, event.paths[0]);
 *   }, 200),
 * );
 * // wait 200ms ...
 * // output: Function debounced after 200ms with baz
 * ```
 *
 * @param fn    The function to debounce.
 * @param wait  The time in milliseconds to delay the function.
 */ // deno-lint-ignore no-explicit-any
export function debounce(fn, wait) {
  let timeout = null;
  let flush = null;
  const debounced = (...args)=>{
    debounced.clear();
    flush = ()=>{
      debounced.clear();
      fn.call(debounced, ...args);
    };
    timeout = setTimeout(flush, wait);
  };
  debounced.clear = ()=>{
    if (typeof timeout === "number") {
      clearTimeout(timeout);
      timeout = null;
      flush = null;
    }
  };
  debounced.flush = ()=>{
    flush?.();
  };
  Object.defineProperty(debounced, "pending", {
    get: ()=>typeof timeout === "number"
  });
  return debounced;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImh0dHBzOi8vZGVuby5sYW5kL3N0ZEAwLjIxNy4wL2FzeW5jL2RlYm91bmNlLnRzIl0sInNvdXJjZXNDb250ZW50IjpbIi8vIENvcHlyaWdodCAyMDE4LTIwMjQgdGhlIERlbm8gYXV0aG9ycy4gQWxsIHJpZ2h0cyByZXNlcnZlZC4gTUlUIGxpY2Vuc2UuXG4vLyBUaGlzIG1vZHVsZSBpcyBicm93c2VyIGNvbXBhdGlibGUuXG5cbi8qKlxuICogQSBkZWJvdW5jZWQgZnVuY3Rpb24gdGhhdCB3aWxsIGJlIGRlbGF5ZWQgYnkgYS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