gpt4 book ai didi

javascript - 如何通过递归使用 setTimeout 来等待在 JavaScript 中定义变量?

转载 作者:行者123 更新时间:2023-11-29 16:45:21 24 4
gpt4 key购买 nike

我想等到storage.get('session')!=null,然后执行回调.

我遇到的问题是,我的递归 setTimeout 方法正在呈指数级运行,而不是每秒检查一次是否定义了变量。

结果是 waitForElement 每秒执行数千次,这是我不希望的。我希望它每 1 秒执行一次,直到 storage.get('session')!=null

waitForElement(function(){
console.log("DONE!");
});

function waitForElement(callback){
if(storage.get('session')!=null)
{
console.log("session exists now");
if(typeof callback=="function")
{
callback();
}
}
else
{
console.log("session still does not exist. Checking again in 1 second");

//ISSUE: THIS RUNS IMMEDIATELY AND FOREVER!
setTimeout(waitForElement(function(cb){
if(typeof cb == "function"){
cb();
}
}), 1000);
}
}

最佳答案

你根本不应该使用超时——Promises 是如今这种异步处理的首选模型,例如

function login() {
return new Promise((resolve, reject) => {
// do something that creates the session
if (successful) {
resolve();
} else {
reject();
}
})
}

// promise that will eventually be resolve when the user logs in
var loggedIn = login();

// multiple (potentially parallel) actions
loggedIn.then(doSomething);
loggedIn.then(doSomethingElse);

// serial actions
loggedIn.then(doFirstThing).then(doSecondThing);

关于javascript - 如何通过递归使用 setTimeout 来等待在 JavaScript 中定义变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42079262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com