我想加载大量文本。在伪代码中,这就是我想要实现的目标:
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()将创建所需的行为。否则,所有内容都会同时打印。
有什么想法吗?
附注我不想加载懒惰。我希望加载整个内容,但将中间结果打印到屏幕上。
编辑1:添加反例
最佳答案
您可以使用setTimeout
轻松实现此效果。
示例(基于您的伪代码):
const first = "Some text"
print first
setTimeout(() => {
const second = "Some more text"
print second
})
如果您有超过 2 个步骤,请考虑使用 Promise(以避免宽缩进):
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 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()
关于Javascript:分几步显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46023289/