Trying to write a function, that does work for one element in the array - and after time, repeats the same work for the next element (for each element in the array). Array consists of <span> elements.
Current function does work for all the elements in the same time.
const wordIntroGroup = document.getElementsByClassName("word");
const forwardBut = document.getElementById("forward");
forwardBut.addEventListener("click", forward);
function forward() {
const y = wordIntroGroup;
for (let i = 0; i < y.length; i++) {
setTimeout(function() {
console.log(y[i]);
}, 2000)
}
}
<p>
<span class="word">Naw,</span>
<span class="word">while</span>
<span class="word">you're</span>
<span class="word">here</span>
</p>
<span id="forward" class="material-icons">
fast_forward
</span>
Your for loop runs every call of your setTimeout function at the same time. So everything will occur 2000ms after the for loop runs. The simplest solution would be to extend the setTimout duration by that of the current location in the array.
setTimeout(function (){
console.log(y[i]);
}, 2000*i) // multiply your duration by i, the index of your current element in the array
Also your syntax error is you didn't close the function forward at the end of your script