简体   繁体   English

如何在反应中停止递归 setTimeout 函数(clearTimeout 不起作用)?

[英]How to stop recursive setTimeout function in react (clearTimeout not working)?

Thanks for taking a look at this.感谢您查看此内容。 I am making an api call with recursion to check on a task status update.我正在使用递归进行 api 调用以检查任务状态更新。 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.不起作用的条件是如果状态为 FAILURE,它不会清除超时,但它会进入条件......超时在正确上下文中的函数外部声明。

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";
        }
    }
}

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";
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM