Arthur Otaviano
Arthur Otaviano

Reputation: 13

How to put this JavaScript code into a loop?

I have this piece of code who kinda follows a pattern but I don't know how to make it a loop to simplify.

setTimeout(() => {
    wrapper.classList.add("show-el-1");
    wrapper.classList.add("hide-el-0");
}, 600);

setTimeout(() => {
    wrapper.classList.add("show-el-2");
    wrapper.classList.add("hide-el-1");
}, 1800);

setTimeout(() => {
    wrapper.classList.add("show-el-3");
    wrapper.classList.add("hide-el-2");
}, 3000);

setTimeout(() => {
    wrapper.classList.add("show-el-4");
    wrapper.classList.add("hide-el-3");
}, 4200);

It adds 1200 in every setTimeout duration, and changes the show-el-x and hide-el-y numbers.

Upvotes: 1

Views: 73

Answers (3)

Ravi Chaudhary
Ravi Chaudhary

Reputation: 670

If you just want to keep this running i.e. updating class after every timeout, then you could go for recursive approach as the snippet below, else for loop could be a more readable and easy to understand solution

let newTimeout = 600;
let firstClass= 1;
const func1 = () => {
    wrapper.classList.add(`show-el-${firstClass}`);
    wrapper.classList.add(`hide-el-${firstClass -1}`);
    newTimeout += 1200;
    firstClass += 1;
    setTimeout(func1, newTimeout);
};
setTimeout(func1, newTimeout);

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89214

You can use a for loop like so:

for(let i = 0; i < 4; i++){
    setTimeout(() => {
        wrapper.classList.add("show-el-" + (i + 1));
        wrapper.classList.add("hide-el-" + i);
    }, 600 + i * 1200);
}

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Something like this should get you going

for (let i = 0; i < 4; i++) {
  const delay = 600 + (i * 1200)
  setTimeout(() => {
    wrapper.classList.add("show-el-" + (i + 1));
    wrapper.classList.add("hide-el-" + i);
  }, delay);    
}

Upvotes: 1

Related Questions