2017-02-06 50 views
2

我想等到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); 
    } 
} 
+0

什麼把這個變量放入'storage'中? – Alnitak

+0

嘿@Alnitak!有一個'登錄'功能,將它存入存儲器。我遇到的問題是多個函數正在等待'login'完成,但我不希望'login'被多次調用。所以如果它被調用一次,然後等待它定義'會話'。其他所有調用它的人都將等待登錄來設置會話。 – Kayvar

+2

這是那種旨在用於承諾的異步情況。顯示'storage.get()'的示例代碼' – charlietfl

回答

5

根本不應該使用超時 - 承諾是目前這種異步處理的首選模型,例如,

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); 
0

這是因爲你馬上調用函數waitForElement當你設置你的超時時間。試試這個

var callback = function(cb){ 
    if(typeof cb == "function"){ 
     cb(); 
    } 
} 

setTimeout(waitForElement.bind(this, callback), 1000); 
0

你正在立即調用waitForElement。你需要傳遞一個基本上沒有「()」的函數名的函數引用。鑑於你的函數沒有「this」,所以不需要擔心這種情況的上下文。

setTimeout(function() { 
    waitForElement(function(cb){ 
     if(typeof cb == "function"){ 
      cb(); 
     } 
    }); 
}, 1000); 

另外值得注意的是,你永遠不會傳遞任何東西到回調函數中。