When using setTimeout in a loop, I noticed that all the operations are executed only after the loop ends. I followed the advice from multiple articles and tried putting setTimeout in a separate function, but it didn't make any difference. Here is the simple code snippet:
function printNumber(i)
{
setTimeout( function() {console.log(i);}, 2000);
}
for (let i=0; i<5; i++)
{
printNumber(i);
}
Instead of printing the numbers one by one as expected, it prints them all at once:
0 1 2 3 4