Javascript:在几个步骤中显示文本
问题描述:
我想加载大量的文本。在伪代码,这是我想什么来实现: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:增加了反例
答
可以轻松实现使用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
什么大小的文本,你正试图加载? –
@RakeshChouhan第一个字符串是几个句子。第二个字符串是500k +个字符。 –
您是否正在考虑像millisec计时器和每millisec它打印一个字符,模拟“动画数字文本”? –