You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
902 B

4 years ago
  1. 'use strict';
  2. module.exports = prompt => {
  3. prompt.timers = prompt.timers || {};
  4. let timers = prompt.options.timers;
  5. if (!timers) return;
  6. for (let key of Object.keys(timers)) {
  7. let opts = timers[key];
  8. if (typeof opts === 'number') {
  9. opts = { interval: opts };
  10. }
  11. create(prompt, key, opts);
  12. }
  13. };
  14. function create(prompt, name, options = {}) {
  15. let timer = prompt.timers[name] = { name, start: Date.now(), ms: 0, tick: 0 };
  16. let ms = options.interval || 120;
  17. timer.frames = options.frames || [];
  18. timer.loading = true;
  19. let interval = setInterval(() => {
  20. timer.ms = Date.now() - timer.start;
  21. timer.tick++;
  22. prompt.render();
  23. }, ms);
  24. timer.stop = () => {
  25. timer.loading = false;
  26. clearInterval(interval);
  27. };
  28. Reflect.defineProperty(timer, 'interval', { value: interval });
  29. prompt.once('close', () => timer.stop());
  30. return timer.stop;
  31. }