Commit b5290ce0 authored by Filipa Lacerda's avatar Filipa Lacerda

Simplify backoff algorithm

parent 29c284cb
...@@ -307,40 +307,37 @@ ...@@ -307,40 +307,37 @@
* @example * @example
* ``` * ```
* backOff(function (next, stop) { * backOff(function (next, stop) {
* // Let's perform this function repeatedly for 60s * // Let's perform this function repeatedly for 60s or for the timeout provided.
* doSomething() *
* .then(function (importantValue) { * ourFunction()
* // importantValue is not exactly what we * .then(function (result) {
* // need so we need to try again * // continue if result is not what we need
* next(); * next();
* *
* // importantValue is exactly what we are expecting so * // when result is what we need let's stop with the repetions and jump out of the cycle
* // let's stop with the repetions and jump out of the cycle * stop(result);
* stop(importantValue);
* }) * })
* .catch(function (error) { * .catch(function (error) {
* // there was an error, let's stop this with an error too * // if there is an error, we need to stop this with an error.
* stop(error); * stop(error);
* }) * })
* }, 60000) * }, 60000)
* .then(function (importantValue) {}) * .then(function (result) {})
* .catch(function (error) { * .catch(function (error) {
* // deal with errors passed to stop() * // deal with errors passed to stop()
* }) * })
* ``` * ```
*/ */
w.gl.utils.backOff = (fn, timeout = 600000) => { w.gl.utils.backOff = (fn, timeout = 60000) => {
let nextInterval = 2000; let nextInterval = 2000;
const checkTimedOut = (timeoutMax, startTime) => currentTime => const startTime = (+new Date());
(currentTime - startTime > timeoutMax);
const hasTimedOut = checkTimedOut(timeout, (+new Date()));
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const stop = arg => ((arg instanceof Error) ? reject(arg) : resolve(arg)); const stop = arg => ((arg instanceof Error) ? reject(arg) : resolve(arg));
const next = () => { const next = () => {
if (!hasTimedOut((+new Date()))) { if ((+new Date()) - startTime < timeout) {
setTimeout(fn.bind(null, next, stop), nextInterval); setTimeout(fn.bind(null, next, stop), nextInterval);
nextInterval *= 2; nextInterval *= 2;
} else { } else {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment