I want to display the progress of a loop function like this ‘1 of total 1000’. I use this code, but in #mycontent
article displayed only the last value of i
.
for (i = 1; i <= 1000; i += 1) {
$('#mycontent article').html(i + ' of total 1000');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="mycontent">
<article></article>
</div>
2
Answers
JavaScript is single-threaded. In this case that means this loop will run to completion before the UI updates, so the UI will only ever see the last change.
Taking a step back… How visually fast do you want the UI to update? Even if the UI were updating, this would be so fast that it wouldn’t really matter. How about an interval of, say, 10ms? The keyword there is "interval", as you can use
setInterval
to achieve this. For example:The execution of your code is blocked until the loop finishes – therefore you see only the last value.
A JavaScript interval might be used, but instead of
setInterval
orsetTimeout
you might use the preferred requestAnimationFrame (for smoother animation and performance):Also, you don’t need JavaScript, (well as soon as Firefox implements this) – it can be done in pure CSS with
@property
andcounter
: