gpt4 book ai didi

javascript - 在完成按钮处理程序之前更改 javascript 元素

转载 作者:行者123 更新时间:2023-12-01 02:34:07 25 4
gpt4 key购买 nike

我想在按钮处理程序运行时更改段落的内容,而不是等待按钮处理程序完成。这是我的代码:

Output: <p id="output"></p><br><br>
<input type="button" onclick="buttonPressed()" value="submit" id="button"><br><br>

<script>

function buttonPressed(){
console.log("output 2")
document.getElementById("output").innerHTML = "output 1"

while (true){
// doing something that takes a long time
}

}

console.log("output 1")
document.getElementById("output").innerHTML = "output 1"

</script>

按下按钮后,我希望输出显示“输出 2”,而不必等待按钮处理程序完成。我在按钮处理程序中有 while true 来演示这一点,实际上我不会有 while true,而是需要一段时间的某种过程。我想让用户知道此过程已经开始,他们应该等待它完成。

感谢您的帮助

最佳答案

您的输出未显示的原因是浏览器线程正忙于执行当前任务(您的函数)。因此,浏览器无法重新绘制显示更新输出的页面。

为了解决这个问题,您需要使用两个单独的任务。实现此目的的一种方法是简单地在超时时运行长时间运行的代码。

function buttonPressed(){
console.log("output 2")
writeOutput("output 2")

setTimeout(function(){ //use a separate task and allow the page to draw
while (true){
// doing something that takes a long time
}
},4);
}

顺便说明一下,这里使用 4 是因为由于浏览器限制和 html5 spec,4 毫秒通常是一次超时可以使用的最短时间。

关于javascript - 在完成按钮处理程序之前更改 javascript 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48068623/

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