task.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.makeWaitForNextTask = makeWaitForNextTask;
  6. /**
  7. * Copyright (c) Microsoft Corporation.
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. // See https://joel.tools/microtasks/
  22. function makeWaitForNextTask() {
  23. // As of Mar 2021, Electron v12 doesn't create new task with `setImmediate` despite
  24. // using Node 14 internally, so we fallback to `setTimeout(0)` instead.
  25. // @see https://github.com/electron/electron/issues/28261
  26. if (process.versions.electron) return callback => setTimeout(callback, 0);
  27. if (parseInt(process.versions.node, 10) >= 11) return setImmediate;
  28. // Unlike Node 11, Node 10 and less have a bug with Task and MicroTask execution order:
  29. // - https://github.com/nodejs/node/issues/22257
  30. //
  31. // So we can't simply run setImmediate to dispatch code in a following task.
  32. // However, we can run setImmediate from-inside setImmediate to make sure we're getting
  33. // in the following task.
  34. let spinning = false;
  35. const callbacks = [];
  36. const loop = () => {
  37. const callback = callbacks.shift();
  38. if (!callback) {
  39. spinning = false;
  40. return;
  41. }
  42. setImmediate(loop);
  43. // Make sure to call callback() as the last thing since it's
  44. // untrusted code that might throw.
  45. callback();
  46. };
  47. return callback => {
  48. callbacks.push(callback);
  49. if (!spinning) {
  50. spinning = true;
  51. setImmediate(loop);
  52. }
  53. };
  54. }