-2

I want that blue color apply to each line after 500ms. I am new to JavaScript I tried everything but nothing work..

here is the code:

let para = document.getElementsByTagName("p");
for (let index = 0; index < para.length; index++) {
  function timer() {
    para[index].classList.toggle("blue");
  }
  setInterval(timer, 500);
}
.blue {
  color: blueviolet;
}
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, ratione.
</p>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, ratione.
</p>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, ratione.
</p>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, ratione.
</p>
vighnesh153
  • 4,354
  • 2
  • 13
  • 27
IMRAN H
  • 11
  • 4
  • Does this answer your question? [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – DBS Nov 04 '22 at 16:52
  • Your code seems to work as it is. Please define "_nothing work_". – Teemu Nov 04 '22 at 16:52
  • Not clear on the ask here. From the code above, it looks like it is applying your color every 500ms. If you want to do it only once, you can change the `toggle` to `add` and `setInterval` to `setTimeout`. – vighnesh153 Nov 04 '22 at 16:52

2 Answers2

1

This will toggle the blue on every element every 500ms...

You want something like this:

let i = 0, els = document.querySelectorAll('p');
//the selector is the same but looks better and is more readable.

setInterval(() => {
    els[i++ % els.length].classList.toggle('blue');
}, 500);
Dr. Vortex
  • 505
  • 1
  • 3
  • 16
-2

Try this:

para[index].classList.add("blue");
milner236
  • 37
  • 9