1

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.

2

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);    
}

Comments

0

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);

2 Comments

Did you recognize that the class names change too?
fixed it. didn't notice earlier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.