Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 6914  / 7 Years ago, thu, september 21, 2017, 12:00:00

Lets say i have an array like this:



var arr = [0,1,2,3,4];


so i want to make a for loop that loops through the array and console logs every item, but i want it to console log separately every item and each item will be console logged a second after the previous item, how can i do this?


More From » arrays

 Answers
8

You can use an interval.
Here is an example:





var arr = [0,1,2,3,4];
var index = 0;
setInterval(function(){
console.log(arr[index++ % arr.length]);
}, 1000)





The example above will loop through the array more then once. If you want to loop the array only once, you can stop the interval when all the elements were logged.





var arr = [0,1,2,3,4];
var index = 0;
var interval = setInterval(function(){
console.log(arr[index++]);
if(index == arr.length){
clearInterval(interval);
}
}, 1000)




[#17923] Wednesday, September 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lidialyrick

Total Points: 737
Total Questions: 104
Total Answers: 89

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;