0

Thanks for taking a look at this. I am making an api call with recursion to check on a task status update. I had implemented this function last week, and it was working?? Not sure why it doesn't anymore. The conditional that doesn't work is if the status is a FAILURE, it doesn't clearout the timeout, but it does enter the conditional.... Timeout is declared outside the function in the correct context.

export async function exponentialBackoff (checkStatus, task_id, timeout, max, delay, callback) {
    let status = await checkStatus(task_id);
    if (status === "SUCCESS") {
        callback();
    } else {
        if (status === "PENDING") {
            timeout = setTimeout(function() {
                return exponentialBackoff(checkStatus, task_id, timeout, --max, delay * 2, callback);
            }, delay);
        }  else if (status === "FAILURE" || max === 0){
            clearTimeout(timeout);
            return "FAILURE";
        }
    }
}
anongal
  • 45
  • 2
  • 8
  • 1
    If you enter the "FAILURE" conditional but the `clearTimeout` doesn't work, then it must mean you're not feeding it the correct timeout ID... or there are more than you realize got started. You could consider clearing them all with something like this: https://stackoverflow.com/questions/8860188/javascript-clear-all-timeouts. Also consider using your debugger and/or printing some `console.log()` messages to illuminate the issue. – Marc Oct 29 '20 at 21:48
  • Awesome thanks so much the approach with window.clearTimeout works. – anongal Oct 29 '20 at 21:53

1 Answers1

0

It looks like a callback hell. I would strongly recommend you to avoid name shadowing and overwriting the arguments.

Also - I believe you don't want to keep the previous timeout alive if a next one was called?

let timeoutInstance;

const clear = (tm) => {
   if (tm) clearTimeout(tm);
};

export async function exponentialBackoff (checkStatus, task_id, max, delay, callback) {
    let status = await checkStatus(task_id);
    if (status === "SUCCESS") {
        callback();
    } else {
        if (status === "PENDING") {
            clear(timeoutInstance);

            timeoutInstance = setTimeout(function() {
                return exponentialBackoff(checkStatus, task_id, --max, delay * 2, callback);
            }, delay);
        }  else if (status === "FAILURE" || max === 0){
            clear(timeoutInstance);

            return "FAILURE";
        }
    }
}
kind user
  • 40,029
  • 7
  • 67
  • 77