Javascript:分几个步骤显示文本

时间:2017-09-03 12:06:22

标签: javascript

我想加载大量文字。在伪代码中,这就是我想要实现的目标:

located in /tmp/deployment/config/etc#nginx#nginx.conf

而不是:

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

但这只有在我输入导致页面在继续之前被绘制/刷新的东西时才有效。例如,在加载任何其他内容之前的alert()将创建所需的行为。否则,所有内容都会同时打印。

有什么想法吗?

P.S。我不是想加载懒惰。我希望加载整个内容,但将中间结果打印到屏幕上。

编辑1:添加了反例

1 个答案:

答案 0 :(得分:3)

您可以使用setTimeout轻松达到此效果。

示例(基于您的伪代码):

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

如果您有两个以上的步骤,请考虑使用promises(以避免广泛的缩进):

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()