idleValue.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * this run the callback when CPU is idle. Will fallback to setTimeout if
  3. * the browser doesn't support requestIdleCallback
  4. */
  5. export var runWhenIdle;
  6. (function () {
  7. if (typeof requestIdleCallback !== 'undefined' &&
  8. typeof cancelIdleCallback !== 'undefined') {
  9. // use native requestIdleCallback
  10. runWhenIdle = function (runner, timeout) {
  11. var handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout: timeout } : undefined);
  12. var disposed = false;
  13. return function () {
  14. if (disposed) {
  15. return;
  16. }
  17. disposed = true;
  18. cancelIdleCallback(handle);
  19. };
  20. };
  21. }
  22. else {
  23. // use setTimeout as hack
  24. var dummyIdle_1 = Object.freeze({
  25. didTimeout: true,
  26. timeRemaining: function () {
  27. return 15;
  28. },
  29. });
  30. runWhenIdle = function (runner) {
  31. var handle = setTimeout(function () { return runner(dummyIdle_1); });
  32. var disposed = false;
  33. return function () {
  34. if (disposed) {
  35. return;
  36. }
  37. disposed = true;
  38. clearTimeout(handle);
  39. };
  40. };
  41. }
  42. })();
  43. /**
  44. * a wrapper of a executor so it can be evaluated when it's necessary or the CPU is idle
  45. *
  46. * the type of the returned value of the executor would be T
  47. */
  48. var IdleValue = /** @class */ (function () {
  49. function IdleValue(executor) {
  50. var _this = this;
  51. this.didRun = false;
  52. this.selfExecutor = function () {
  53. try {
  54. _this.value = executor();
  55. }
  56. catch (err) {
  57. _this.error = err;
  58. }
  59. finally {
  60. _this.didRun = true;
  61. }
  62. };
  63. this.disposeCallback = runWhenIdle(function () { return _this.selfExecutor(); });
  64. }
  65. IdleValue.prototype.hasRun = function () {
  66. return this.didRun;
  67. };
  68. IdleValue.prototype.dispose = function () {
  69. this.disposeCallback();
  70. };
  71. IdleValue.prototype.getValue = function () {
  72. if (!this.didRun) {
  73. this.dispose();
  74. this.selfExecutor();
  75. }
  76. if (this.error) {
  77. throw this.error;
  78. }
  79. return this.value;
  80. };
  81. return IdleValue;
  82. }());
  83. export { IdleValue };
  84. //# sourceMappingURL=idleValue.js.map