我想等到storage.get('session')!=null
,然後執行callback
。如何使用setTimeout和遞歸來等待在JavaScript中定義變量?
我遇到的問題是,我的遞歸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);
}
}
什麼把這個變量放入'storage'中? – Alnitak
嘿@Alnitak!有一個'登錄'功能,將它存入存儲器。我遇到的問題是多個函數正在等待'login'完成,但我不希望'login'被多次調用。所以如果它被調用一次,然後等待它定義'會話'。其他所有調用它的人都將等待登錄來設置會話。 – Kayvar
這是那種旨在用於承諾的異步情況。顯示'storage.get()'的示例代碼' – charlietfl