wait.js 901 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. const internals = {
  3. maxTimer: 2 ** 31 - 1 // ~25 days
  4. };
  5. module.exports = function (timeout, returnValue, options) {
  6. if (typeof timeout === 'bigint') {
  7. timeout = Number(timeout);
  8. }
  9. if (timeout >= Number.MAX_SAFE_INTEGER) { // Thousands of years
  10. timeout = Infinity;
  11. }
  12. if (typeof timeout !== 'number' && timeout !== undefined) {
  13. throw new TypeError('Timeout must be a number or bigint');
  14. }
  15. return new Promise((resolve) => {
  16. const _setTimeout = options ? options.setTimeout : setTimeout;
  17. const activate = () => {
  18. const time = Math.min(timeout, internals.maxTimer);
  19. timeout -= time;
  20. _setTimeout(() => (timeout > 0 ? activate() : resolve(returnValue)), time);
  21. };
  22. if (timeout !== Infinity) {
  23. activate();
  24. }
  25. });
  26. };