How do I add a delay in a JavaScript loop? How do I add a delay in a JavaScript loop? javascript javascript

How do I add a delay in a JavaScript loop?


The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.

You may want to use something like this instead:

var i = 1;                  //  set your counter to 1function myLoop() {         //  create a loop function  setTimeout(function() {   //  call a 3s setTimeout when the loop is called    console.log('hello');   //  your code here    i++;                    //  increment the counter    if (i < 10) {           //  if the counter < 10, call the loop function      myLoop();             //  ..  again which will trigger another     }                       //  ..  setTimeout()  }, 3000)}myLoop();                   //  start the loop