I am trying to write a for loop that has a delay between running each iteration. I thought Id go about it by using setTimeout()
as follows.
Input:
for (let i=0;i<3;i++){
setTimeout(()=>{console.log("hi")},10000)
}
Output:
hi
hi
hi
What seems to be happening is that its waiting 10 seconds and then runs the entire for loop, rather than waiting 10 seconds to run each iteration of the for loop. After the first hi
is shown to the console, the other 2 follow instantaneously. Why is this the case, rather than a delayed logging of hi
and how can I go about doing this?