Browse Source

Add the code.

Herbert Vojčík 8 years ago
parent
commit
6e8291c64c
1 changed files with 48 additions and 0 deletions
  1. 48 0
      index.js

+ 48 - 0
index.js

@@ -0,0 +1,48 @@
+// Defines a module that works in Node and AMD.
+(function (define) {
+    define(function (require, exports, module) {
+
+        function RecurringPromise(factory, step) {
+            this.timer = null;
+            this.factory = factory;
+            this.step = step;
+            this.shouldStop = false;
+        }
+
+        RecurringPromise.prototype.loop = function () {
+            var self = this;
+            this.promise = new Promise(function (resolve, reject) {
+                function step() {
+                    self.timer = null;
+                    self.factory()
+                        .then(resolve, function () {
+                            if (self.shouldStop) reject.apply(null, arguments);
+                            else self.timer = setTimeout(step, self.step || 100);
+                        });
+                }
+
+                step();
+            });
+            return this.promise;
+        };
+
+        RecurringPromise.prototype.stop = function () {
+            this.shouldStop = true;
+            return this.promise || Promise.resolve();
+        };
+
+        RecurringPromise.prototype.stopAndForget = function () {
+            return this.stop().catch(function () {
+            });
+        };
+
+        return RecurringPromise;
+    });
+
+}( // Help Node out by setting up define.
+    typeof module === 'object' && module.exports && typeof define !== 'function'
+        ? function (factory) {
+        module.exports = factory(require, exports, module);
+    }
+        : define
+));