Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
function invoked for each element in array, in time intervals

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!