![](/img/trans.png)
[英]How to use setTimeout with a "do while" loop in Javascript?
[英]How do I use setTimeout with recursion to wait for a variable to be defined in JavaScript?
我想等到storage.get('session')!=null
,然后执行callback
。
我遇到的问题是我的递归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);
}
}
您根本不应该使用超时-如今,Promise是此类异步处理的首选模型,例如
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);
这是因为设置超时后,您将立即调用waitForElement
函数。 尝试这个
var callback = function(cb){
if(typeof cb == "function"){
cb();
}
}
setTimeout(waitForElement.bind(this, callback), 1000);
您将立即调用waitForElement。 您需要传递一个函数引用,该函数引用基本上是一个没有“()”的函数名称。 鉴于您的函数没有“ this”,因此无需担心这种情况的上下文。
setTimeout(function() {
waitForElement(function(cb){
if(typeof cb == "function"){
cb();
}
});
}, 1000);
另外要注意的是,您绝不会将任何内容传递给回调函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.