2017-09-17 19 views
0

我有一個跨度和一個按鈕。當我按下按鈕時,我想改變範圍並調用一個函數(獲得一個帶有keythereum的私鑰,但我認爲它並不重要),這需要很長時間才能完成(通常是5-10秒)。跨度文本不會立即用Javascript更改

window.myFunction = function() { 

// checking the text of the span 
    console.log(document.getElementById("span").textContent); 

//changing my span 
    document.getElementById("span").textContent = "Please wait..." 

// console outputs the new span showing that the textContent has changed 
    console.log(document.getElementById("span").textContent); 

// getting the password from an input field 
    var password = document.getElementById("password").value; 

// calling the function to get a private Key from an object, 
// locked with the password I just got from the input field 
    try { 
     var privateKey = keythereum.recover(password, keyObj); 
     console.log(privateKey.toString('hex')); 
    } catch (error) { 
     console.log(error); 
    } 
} 

當我按下按鈕時,我希望span變成像「請稍候...」之類的東西,然後調用該函數。但是當我按下按鈕時會發生什麼情況,我得到第一個控制檯日誌,其中包含span的舊textContent,接下來我使用新的textContent獲取新的控制檯日誌,但是我看不到屏幕上的更改。接下來在keythereum函數被調用時沒有任何反應。當功能完成它的任務並且privateKey被記錄時,範圍僅在視覺上改變。 有沒有一種方法可以在函數被調用之前立即直觀地改變範圍?

+0

請注意,您閱讀'#wallet - 警告'並設置'#span'。無論如何,您需要一個計時器讓瀏覽器呈現新內容。 – Teemu

+0

我用跨度爲解釋在這裏,對不起 都是錢包預警在我的代碼 –

回答

1

keythereum.recover顯然確實同步阻擋(例如,使用alertpromptconfirm)。這可以防止更改被繪製。

爲了讓瀏覽器有機會油漆的變化,通過setTimeout安排在任務隊列中的下一個任務文本更改後的代碼:

window.myFunction = function() { 

// checking the text of the span 
    console.log(document.getElementById("wallet-warning").textContent); 

//changing my span 
    document.getElementById("span").textContent = "Please wait..." 

//***do the rest after the browser has a chance to repain 
    setTimeout(function()) { 
// console outputs the new span showing that the textContent has changed 
     console.log(document.getElementById("wallet-warning").textContent); 

// getting the password from an input field 
     var password = document.getElementById("password").value; 

// calling the function to get a private Key from an object, 
// locked with the password I just got from the input field 
     try { 
      var privateKey = keythereum.recover(password, keyObj); 
      console.log(privateKey.toString('hex')); 
     } catch (error) { 
      console.log(error); 
     } 
    }, 50); // 50ms 
} 

50ms的是幾乎無法察覺到人類,但它是一個很長時間的瀏覽器。 (我曾經使用0,它計劃它儘快運行一旦當前任務[和它的microtasks]完成,但在這種情況下,Firefox並不總是重繪。)

0

使用類似setTimeout()的方法撥打keythereum.recover()異步電話。跨度文本不會更新,因爲在您的JavaScript完成之前,瀏覽器不會更新DOM。

+0

有一個異步功能選項: 'keythereum.recover(密碼,keyObject,功能(專用密鑰){// 做的東西 }) ; ' 但問題是我不能捕捉任何錯誤 –