throbber.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. var compose = require("es5-ext/function/#/compose")
  3. , callable = require("es5-ext/object/valid-callable")
  4. , d = require("d")
  5. , validTimeout = require("timers-ext/valid-timeout");
  6. var chars = "-\\|/", l = chars.length, ThrobberIterator;
  7. ThrobberIterator = function () {
  8. // no setup needed
  9. };
  10. Object.defineProperties(ThrobberIterator.prototype, {
  11. index: d(-1),
  12. running: d(false),
  13. next: d(function () {
  14. var str = this.running ? "\u0008" : "";
  15. if (!this.running) this.running = true;
  16. return str + chars[(this.index = (this.index + 1) % l)];
  17. }),
  18. reset: d(function () {
  19. if (!this.running) return "";
  20. this.index = -1;
  21. this.running = false;
  22. return "\u0008";
  23. })
  24. });
  25. module.exports = exports = function (write, interval /*, format*/) {
  26. var format = arguments[2], token, iterator = new ThrobberIterator();
  27. callable(write);
  28. interval = validTimeout(interval);
  29. if (format !== undefined) write = compose.call(write, callable(format));
  30. return {
  31. start: function () {
  32. if (token) return;
  33. token = setInterval(function () { write(iterator.next()); }, interval);
  34. },
  35. restart: function () {
  36. this.stop();
  37. this.start();
  38. },
  39. stop: function () {
  40. if (!token) return;
  41. clearInterval(token);
  42. token = null;
  43. write(iterator.reset());
  44. }
  45. };
  46. };
  47. Object.defineProperty(exports, "Iterator", d(ThrobberIterator));