gpt4 book ai didi

Javascript:分几步显示文本

转载 作者:行者123 更新时间:2023-11-29 19:02:16 24 4
gpt4 key购买 nike

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

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 个步骤,请考虑使用 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()

关于Javascript:分几步显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46023289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com