JavaScript不会在按钮触发的重复操作上更新状态Div [英] JavaScript Does Not Update Status Div On Repeated Actions Triggered by Button
问题描述
我有以下JavaScript.附带的代码是相当复杂的自动生成的JavaScript的极其简化的版本,该JavaScript在许多对象上启动相同的功能(不是循环的,而是生成的一堆函数调用).
I have the following JavaScript. The attached code is extremely simplified version of rather complex auto-generated JavaScript that launches the same function on lots of objects (not in loop, but just a bunch of function calls generated).
问题在于代码应该在每次启动函数时更新一个元素.但是,这不会发生.相反,当我按下按钮时,它只会冻结并更新所有状态(执行完成")后才能更新状态.那么为什么在以下代码中每次调用 long_function()
时都不会更新该元素(以及如何解决该问题):
The problem is that the code is supposed to update an element on each launch of the function. However, that does not happen. Instead, when I press the button it freezes and updates status only after all functions are performed (to "Done"). So why the element is not updated on each call of long_function()
in the following code (and how do I fix that):
<html>
<body>
<h1 id="status">Not yet started</h1>
<button onclick="perform()"> Start! </button>
<script type="text/javascript">
function sleepFor( sleepDuration ){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
function long_function(number)
{
document.getElementById("status").innerHTML = number;
sleepFor(1000);
}
function perform(number) {
long_function(1);
long_function(2);
document.getElementById("status").innerHTML = "Done";
}
</script>
</body>
</html>
(问题发生在Google Chrome和Safari中)
(The problem happens in Google Chrome and Safari)
(睡眠功能是从的答案中提取的.()?)
推荐答案
这就是我所了解的情况:
This is how I understand what happens:
- 函数
perform()
运行,并且它首先调用long_function(1)
. -
innerHTML
调用被发送. - 调用
sleepFor(1000)
函数,但浏览器尚未呈现innerHTML
更改. - 实时编译器在
sleepFor()
中的while
循环中运行,该循环本质上被阻止(它将停止运行其他JavaScript代码)但也会阻止浏览器呈现.) - 完成
while
循环后,JavaScript会继续将元素的innerHTML
设置为完成",但始终无法呈现number
在long_function()
中.
- Function
perform()
runs, and it callslong_function(1)
first. - The
innerHTML
call gets sent. - The
sleepFor(1000)
function gets called, but the browser hasn't rendered theinnerHTML
change yet. - The live compiler runs through the
while
loop insleepFor()
, which is blocking by nature (it stops other JavaScript code from running but it also stops the browser from rendering). - Once the
while
loop is done, JavaScript proceeds to set theinnerHTML
of your element to "Done", but it never got to render thenumber
inlong_function()
.
如果您想对事件循环,阻塞和非阻塞JavaScript进行有趣的观察,请参考以下资源:
If you want an interesting watch on the event loop, blocking and non-blocking JavaScript, here are some resources:
由于标题( innerHTML
实际上并不异步运行),这个问题有点令人误解,但是答案很有趣:
This question is a bit misleading because of the title (innerHTML
doesn't actually run asynchronously) but the answers are interesting:
这篇关于JavaScript不会在按钮触发的重复操作上更新状态Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!