328101b1d69de523e764d077cc51fd4871be2d7a16c074d28bdc2a566bc3512da13d43e133dc21c39a3f3dcbe09cb15b4bd93881b0ae6a4b7dbb25b70bed2b 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. let nextHandle = 1;
  2. // The promise needs to be created lazily otherwise it won't be patched by Zones
  3. let resolved: Promise<any>;
  4. const activeHandles: { [key: number]: any } = {};
  5. /**
  6. * Finds the handle in the list of active handles, and removes it.
  7. * Returns `true` if found, `false` otherwise. Used both to clear
  8. * Immediate scheduled tasks, and to identify if a task should be scheduled.
  9. */
  10. function findAndClearHandle(handle: number): boolean {
  11. if (handle in activeHandles) {
  12. delete activeHandles[handle];
  13. return true;
  14. }
  15. return false;
  16. }
  17. /**
  18. * Helper functions to schedule and unschedule microtasks.
  19. */
  20. export const Immediate = {
  21. setImmediate(cb: () => void): number {
  22. const handle = nextHandle++;
  23. activeHandles[handle] = true;
  24. if (!resolved) {
  25. resolved = Promise.resolve();
  26. }
  27. resolved.then(() => findAndClearHandle(handle) && cb());
  28. return handle;
  29. },
  30. clearImmediate(handle: number): void {
  31. findAndClearHandle(handle);
  32. },
  33. };
  34. /**
  35. * Used for internal testing purposes only. Do not export from library.
  36. */
  37. export const TestTools = {
  38. pending() {
  39. return Object.keys(activeHandles).length;
  40. }
  41. };