Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

Immediate.ts 1.0KB

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