2016-11-07 171 views
0

我必須找到一個按鈕,當它出現。爲了做到這一點,我使用setInterval。當它找到這個按鈕時,它會給出我需要的變量值。我在setTimeout中檢查它,但是在setTimeout(在這些方法之外)之後,我的全局變量變得和setTimeout一樣。如何解決這個問題?我不能更改setInterval內的全局變量es6

let foundValue; 
function findById(id) { 
    let interval = setInterval(() => { 
    if (document.getElementById(id)){ 
     let foundValue = document.getElementById(id); 
     clearInterval(interval); 
    } 
    }, 1000); 
    return foundValue; 
} 
+4

你有兩個'讓foundValue'線。這是故意的嗎? –

+2

刪除第二個讓.......... – Mahi

+0

本質上,你有兩個變量在不同的作用域稱爲同一件事 – Liam

回答

0

這是因爲你重新聲明foundValuesetInterval所以你應該刪除第二個let,例如:

let foundValue; 
function findById(id) { 
    let interval = setInterval(() => { 
    if (document.getElementById(id)){ 
     foundValue = document.getElementById(id); 
     clearInterval(interval); 
    } 
    }, 1000); 
    return foundValue; 
} 
+0

我刪除這些讓但沒有發生 –

+0

它爲我工作如下'console.log(foundInterval)//is undefined' then findById('element_id')'then'console.log(foundInterval)// contains element' – phpchap