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()将创建所需的行为。否则,所有内容都会同时打印。

有什么想法吗?

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

编辑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/

相关文章:

javascript - 使用侧边栏移动内容

javascript - Ajax 调用后,电子邮件被发送多次

Javascript 按年份 DESC、月份 ASC、日期 ASC 对数组中的日期进行排序

javascript - 为目标为 ="_blank"的 URL 显示带有固定消息的弹出窗口

javascript - 使用更少的代码行添加和删除类

javascript - Chart.JS 多个插件不运行

javascript - 访问 $('.class' ).each() 中的前一个元素

javascript - 通过单击 Javascript 中的按钮在表格单元格中设置文本

javascript - 如何跟踪和收集特定字段的所有使用过的依赖 JavaScript

javascript - 同时支持ajax和直接调用的 View 引擎