index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Defines a module that works in Node and AMD.
  2. (function (define) {
  3. define(function (require, exports, module) {
  4. function RecurringPromise(factory, step) {
  5. this.timer = null;
  6. this.factory = factory;
  7. this.step = step;
  8. this.shouldStop = false;
  9. }
  10. RecurringPromise.prototype.loop = function () {
  11. var self = this;
  12. this.promise = new Promise(function (resolve, reject) {
  13. function step() {
  14. self.timer = null;
  15. self.factory()
  16. .then(resolve, function () {
  17. if (self.shouldStop) reject.apply(null, arguments);
  18. else self.timer = setTimeout(step, self.step || 100);
  19. });
  20. }
  21. step();
  22. });
  23. return this.promise;
  24. };
  25. RecurringPromise.prototype.stop = function () {
  26. this.shouldStop = true;
  27. return this.promise || Promise.resolve();
  28. };
  29. RecurringPromise.prototype.stopAndForget = function () {
  30. return this.stop().catch(function () {
  31. });
  32. };
  33. return RecurringPromise;
  34. });
  35. }( // Help Node out by setting up define.
  36. typeof module === 'object' && module.exports && typeof define !== 'function'
  37. ? function (factory) {
  38. module.exports = factory(require, exports, module);
  39. }
  40. : define
  41. ));