You can use a nested setTimout (also called a Chained Timeout) to accomplish this, otherwise the results will display all-at-once at the very end (giving the appearance that only the final one worked).
The pop()
method gets/removes the last array element, so we want to first reverse the array so that the characters are popped-off in their original order, per your question specs. Using pop()
gives us a quick way to run the array once only.
I prefer to use nested setTimeout()
to using setInterval()
because the setTimeout will call itself again as soon as it has finished, whereas setInterval re-runs itself on a timer. Therefore, if there is any delay completing the function the next setInterval will still run as scheduled, meaning that multiple instances of the function could stack up.
let arr = [];
$("button").click(function() {
$('.menu li').each(function(){
arr.push( $(this).text() );
});
arr = arr.reverse();
showChars(arr);
});
function showChars(arr){
if (arr.length === 0) return false;
let chr = arr.pop();
setTimeout(function(){
$('#show').val(chr);
showChars(arr);
},1000);
}
input {
width: 40px;
height: 40px;
text-align:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<input type=text id="show" />
<button>show li in order every 2 seconds</button>
<ul class="menu">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
Chained-Timeout gives a guaranteed slot of free time to the browser; Interval tries to ensure the function it is running executes as close as possible to its scheduled times, at the expense of browser UI availability.
setTimeout or setInterval?