I have a variable that contains HTML code of a bunch of items. I would like to append all these items in two second intervals. The code I have written below appends all of the items at once. I do not understand why it is doing this as the setTimeout() is within the each().
var myVar = "<div class='item'>Item01</div>" +
"<div class='item'>Item02</div>" +
"<div class='item'>Item03</div>";
$(myVar).each( function() {
var value = $(this);
setTimeout( function {
$('.item-list').append(value);
}, 2000);
}
Try this:
Explanation
In your original code, the loop occurs very quickly. Let’s pretend each iteration of the loop takes 1ms. That means that the first item is added 2001ms later, the second item 2002ms later, and the third one 2003ms later.
By getting the index of the item in the array, we can add the first item 2000ms later, the second one 4000ms later, and so on.
Update: Fixed syntax error.