Delay in JavaScript Loop

setTimeout is not the answer when it comes to delay in loops in Javascript. Using setTimeout will cause the first cycle to have the delay and then it will run to the end of the loop from the second time.

for (var i = 1; i < 100; i++)
    setTimeout(function () { console.log('hello');  }, 2000 * i);

The above piece of code is the best solution that I mostly use in my apps for causing delays in Javascript Codes.

Leave a comment

Leave a Reply