Print every element of an array one by one in certain interval | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Print every element of an array one by one in certain interval

I want to take action on the each array element after certain interval, but it's not working, I tried all ways, loops etc. tarr = ["apps", "basic", "foreman", "coconut", "telegram", "php"] tarr.forEach(i => { setTimeout(() => { console.log(i) }, 2000); }) setInterval(() => { for(i = 0; i < tarr.length; i++) { console.log(tarr[i]) } }, 2000); Example, I want it to work like this: print (wait 2 second) print (wait 2 second) print (wait 2 second) print (wait 2 second)

29th Nov 2021, 7:26 PM
Bibek Oli
Bibek Oli - avatar
2 Answers
+ 2
You can multiply the interval by the index to offset the timeout/interval for each subsequent call of the forEach loop to get the desired effect. This will work fine for smaller arrays, but may cause slight time offset issues for very large arrays due to processing time. const arr = [1,2,3,4,5]; const delay = 2000; arr.forEach( (el, i) => { setTimeout(() => console.log(el), delay * i); } ); Here's some more info with other ways to accomplish what you're after. https://stackoverflow.com/questions/45498873/add-a-delay-after-executing-each-iteration-with-foreach-loop Otherwise, don't use the looping feature and create a function for setTimeout or setInterval to call until it has reached the last element and then clear it. Much like what Alex states.
29th Nov 2021, 11:56 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
tarr.forEach(i => { setTimeout(() => { console.log(i); }, 2000); }); This won't work, because each element starts their timer directly after each other. After 2000ms (+ some time to process the forEach) all items land on the call stack and get written to console directly after each other. ----------------- setInterval(() => { for(i = 0; i < tarr.length; i++) { console.log(tarr[i]); } }, 2000); This won't work, because every 2000ms the array is fully written to console. The for loop is inside the interval. ---------------------- What you want is an interval, which outputs a single element of the array, with the index depending on the times the interval has fired. Here are some hints to help you out: - setInterval returns an ID. You can stop an interval with clearInterval(ID) - the interval can also be stopped from inside the callback you passed to setInterval. let id = setInterval( () => { // do something if(/*some condition*/) { clearInterval(id); } }, 2000);
29th Nov 2021, 8:39 PM
Alex
Alex - avatar