2017-09-03 43 views
2

我想加載大量的文本。在僞代碼,這是我想什麼來實現:Javascript:在幾個步驟中顯示文本

var first = "Some text" 
print first 
var second = "Some more text" 
print second 

,而不是:

var first = "Some text" 
var second = "Some more text" 
print first + second 

我一直在使用

$(window).load(function(){} 

嘗試,但這隻適用於如果我把導致頁面在繼續之前被繪製/刷新。例如,在執行其他任何負載之前的alert()會創建所需的行爲。否則,全部同時打印。

任何想法?

P.S.我不想加載懶惰。我想要加載整個內容,但將中間結果打印到屏幕上。

編輯1:增加了反例

+0

什麼大小的文本,你正試圖加載? –

+0

@RakeshChouhan第一個字符串是幾個句子。第二個字符串是500k +個字符。 –

+0

您是否正在考慮像millisec計時器和每millisec它打印一個字符,模擬「動畫數字文本」? –

回答

3

可以輕鬆實現使用setTimeout這個效果。

例(根據您的僞代碼):

const first = "Some text" 
print first 
setTimeout(() => { 
    const second = "Some more text" 
    print second 
}) 

如果你有2層以上的步驟,可以考慮使用承諾(以避免寬的壓痕):

const first = "Some text" 
print first 
new Promise(resolve => setTimeout(() => { 
    const second = "Some more text (1)" 
    print second 
    resolve() 
})).then(() => new Promise(resolve => setTimeout(() => { 
    const third = "Some more text (2)" 
    print third 
    resolve() 
}))).then(() => new Promise(resolve => setTimeout(() => { 
    const fourth = "Some more text (3)" 
    print fourth 
    resolve() 
}))) 

甚至async/await

async function printTexts() { 
    const texts = ["Some text", "Some more text (1)", "Some more text (2)", "Some more text (3)"] 
    for(const text of texts) { 
     print text 
     await new Promise(resolve => setTimeout(resolve)) 
    } 
} 
printTexts() 
+1

我會直接在循環內放置打印文本,而不是在超時。 –

+0

你是對的:現在它好多了。 – ideaboxer