在下面的 HTML 页面中,我希望在 for 循环运行时更新 div。但是,在循环结束之前没有发生div更新?
<!DOCTYPE html>
<html>
<body>
<h1>why div is not updated until the for loop is finished?</h1>
<div id="myBar"></div>
<br>
<button onclick="afficheHeure()">Click Me</button>
<script>
var p1 = document.getElementById("myBar");
function afficheHeure(){
for(i=0; i< 50000; i++){
setInterval(function(){
let d = new Date();
let e = d.getTime();
p1.innerHTML = e;
}, 100);
console.log("i vaut = " + i);
}
}
</script>
</body>
</html>
最佳答案
Javascript 函数是“原子”的,因为它们不会被“异步”函数中断。 setInterval
注册一个异步运行的函数。它会等到没有其他函数正在运行才运行。
因为您正在使用 setInterval
注册函数,所以这些函数在间隔过去之前不会运行(并且当前没有其他 JS 函数正在运行)。然而,setInterval
本身是“非阻塞”的:它只是注册函数然后返回。这意味着它注册的函数尚未运行。
让我们看一下编写我们自己的“setDelayed”函数作为示例(它实际上不会等待特定的时间间隔,但它会让我们注册稍后运行的函数):
const queue = []
function setDelayed (delayedFunction) {
queue.push(delayedFunction)
}
function runDelayed () {
console.info('running delayed functions')
while (queue.length) queue.pop().call()
console.info('done with delayed functions')
}
// now we put or code with the loop
for(let i=0; i< 5; i++){
setDelayed(function(){
let e = new Date().getTime()
console.log({e,i})
})
console.log("registered i value", i)
}
// and now we manually trigger our delayed functions, like JS would normally do automatically
runDelayed()
此外,如果您正在进行 DOM 更新(如您的示例),浏览器实际上会等待您的脚本完成,然后再呈现任何这些更改。因此,如果您的循环需要足够长的时间,浏览器实际上会“卡住”,直到循环完成。有API专门为了防止这种“卡住”。
关于html - 为什么div在for循环完成之前不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63996224/