我正在用貨幣產生“升序”效果。頁面加載,然后極快的計數從 0.00 開始到 API 給出的十進制數。我在 for 回圈中使用 setTimeout 。到這里為止一切正常,但是當 for 回圈結束時,小數點后的數字是 00。如果 API 回傳 $7000.50,HTML 中的最終結果是 $7000.00。我試圖用實際的 API 值更改 innerHTML 元素,但它在 for 回圈之前執行,即使我進行了 .then() 或回呼。
JS:
function getTotalIncome() {
fetch('/Invoices/GetProviderTotalIncome')
.then(res => res.json())
.then(function (data){
for (let i = 0.0; i <= data; i ) {
setTimeout(function () {
document.getElementById('totalIncome').innerHTML = i.toFixed(2)
}, 50)
}
document.getElementById('totalIncome').innerHTML = data.toFixed(2) //Why this is called before the for loop?
})
}
HTML:
<h4 class="text-center">Total Invoices Value:
<b>$<span id="totalIncome"></span></b>
</h4>
uj5u.com熱心網友回復:
一種解決方案可能是將最后一行放在 for 回圈中并讓它在最后一次迭代中執行:
function getTotalIncome() {
fetch('/Invoices/GetProviderTotalIncome')
.then(res => res.json())
.then(function (data){
for (let i = 0.0; i <= data; i ) {
setTimeout(function () {
document.getElementById('totalIncome').innerHTML = i.toFixed(2)
// this will execute on final iteration, when for loop ends
if(i == data ){
document.getElementById('totalIncome').innerHTML = data.toFixed(2)
}
}, 50)
}
})
}
這將導致它在 for 回圈之后執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/343088.html
