首页 > 解决方案 > UI 仅在循环完成后更新

问题描述

我正在html()循环使用。显示仅在循环结束时更新。我console.log之后添加,我在控制台中看到了日志。如果我添加一个,alert我可以看到显示发生变化。

for (i = 0; i < 25; i++) {
  $("#selector").html(" Occurences " + i);
  console.log(" Occurences " + i);
  //alert("something");
  wait(200);
}


function wait(ms) {
  var start = new Date().getTime();
  var end = start;
  while (end < start + ms) {
    end = new Date().getTime();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="selector">Test</div>

https://jsfiddle.net/bhfnaxgk/3/

标签: jquery

解决方案


这是预期的行为,因为for循环while会在处理 UI 时阻止 UI 更新。

假设从代码的上下文中您尝试创建一个显示在 UI 中的增量计数器,您可以使用 jQuery 的animate()方法:

$({
  Counter: 0
}).animate({
  Counter: 25
}, {
  duration: 5000, // 25 iterations * 200ms delay
  easing: 'linear',
  step: n => $('#my_selector').text(`Occurences: ${Math.ceil(n)}`)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="my_selector"></span>


推荐阅读