debounce.ts 751 B

123456789101112131415161718192021222324
  1. import { PromiseDelegate } from '@phosphor/coreutils';
  2. // Copyright (c) Jupyter Development Team.
  3. // Distributed under the terms of the Modified BSD License.
  4. /**
  5. * Returns a debounced function that can be called multiple times safely and
  6. * only executes the underlying function once per `interval`.
  7. *
  8. * @param fn - The function to debounce.
  9. *
  10. * @param interval - The debounce interval; defaults to 500ms.
  11. */
  12. export function debounce(fn: () => any, interval = 500): () => Promise<void> {
  13. let debouncer = 0;
  14. return () => {
  15. const delegate = new PromiseDelegate<void>();
  16. clearTimeout(debouncer);
  17. debouncer = setTimeout(async () => {
  18. delegate.resolve(void (await fn()));
  19. }, interval);
  20. return delegate.promise;
  21. };
  22. }