SimulatedClock.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { __spreadArray, __read } from './_virtual/_tslib.js';
  2. var SimulatedClock =
  3. /*#__PURE__*/
  4. /** @class */
  5. function () {
  6. function SimulatedClock() {
  7. this.timeouts = new Map();
  8. this._now = 0;
  9. this._id = 0;
  10. }
  11. SimulatedClock.prototype.now = function () {
  12. return this._now;
  13. };
  14. SimulatedClock.prototype.getId = function () {
  15. return this._id++;
  16. };
  17. SimulatedClock.prototype.setTimeout = function (fn, timeout) {
  18. var id = this.getId();
  19. this.timeouts.set(id, {
  20. start: this.now(),
  21. timeout: timeout,
  22. fn: fn
  23. });
  24. return id;
  25. };
  26. SimulatedClock.prototype.clearTimeout = function (id) {
  27. this.timeouts.delete(id);
  28. };
  29. SimulatedClock.prototype.set = function (time) {
  30. if (this._now > time) {
  31. throw new Error('Unable to travel back in time');
  32. }
  33. this._now = time;
  34. this.flushTimeouts();
  35. };
  36. SimulatedClock.prototype.flushTimeouts = function () {
  37. var _this = this;
  38. __spreadArray([], __read(this.timeouts), false).sort(function (_a, _b) {
  39. var _c = __read(_a, 2);
  40. _c[0];
  41. var timeoutA = _c[1];
  42. var _d = __read(_b, 2);
  43. _d[0];
  44. var timeoutB = _d[1];
  45. var endA = timeoutA.start + timeoutA.timeout;
  46. var endB = timeoutB.start + timeoutB.timeout;
  47. return endB > endA ? -1 : 1;
  48. }).forEach(function (_a) {
  49. var _b = __read(_a, 2),
  50. id = _b[0],
  51. timeout = _b[1];
  52. if (_this.now() - timeout.start >= timeout.timeout) {
  53. _this.timeouts.delete(id);
  54. timeout.fn.call(null);
  55. }
  56. });
  57. };
  58. SimulatedClock.prototype.increment = function (ms) {
  59. this._now += ms;
  60. this.flushTimeouts();
  61. };
  62. return SimulatedClock;
  63. }();
  64. export { SimulatedClock };