0

I need to set a delay in the execution of a for loop in JavaScript.

Here is my code:

function myFunction1() { var list = document.getElementById('SomeList'); var items = list.getElementsByTagName('li'); for (var i = 0; i < items.length; ++i) { setTimeout(delayLoop, 1500); } } function delayLoop() { alert('Hello'); } 

After adding the "alert('Hello')" code to the delayLoop function, I noticed that the setTimeout function only displays the alert box after the execution of myFunction1().

How can I use setTimeout to slow down each loop through the collection of items to 1500ms?

1

2 Answers 2

1

Maybe this helps

function pause(ms) { ms += new Date().getTime(); while (new Date() < ms){} } 
Sign up to request clarification or add additional context in comments.

Comments

0

You may have to use a callback here

var list = document.getElementById('SomeList'); var items = list.getElementsByTagName('li'); var i = 0; var myFunction1 = function() { if ( i < items.length ) { // Do some code with items[i] i++; setTimeout(myFunction1, 1500); } else { // No more elements return; } } 

This way your myFunction1 will execute every 1.5 seconds.

Comments