Reputation: 467
I'm trying to start if statement from number 0 when the window is loaded but it's ignoring the 0 and starting from 1, can somebody please help me understand how this work.
showAnime = () => {
let counter = 0;
setInterval(() => {
counter++;
if (counter === 0) {
console.log(counter);
// when window is loaded this condition should start first
this.setState({
animateRightOne: "animated fadeInRightBig delay-one"
});
} else if (counter === 1) {
console.log(counter);
this.setState({
animateRightTwo: "animated fadeInRightBig delay-two"
});
} else if (counter === 2) {
console.log(counter);
this.setState({
animateRightThree: "animated fadeInRightBig delay-three"
});
} else if (counter === 3) {
console.log(counter);
this.setState({
animateLeftFour: "animated fadeInLeftBig delay-four"
});
} else if (counter === 4) {
console.log(counter);
this.setState({
animateRightFive: "animated fadeInRightBig delay-five"
});
} else if (counter === 5) {
console.log(counter);
this.setState({
animateRightSix: "animated fadeInRightBig delay-six"
});
} else if (counter === 6) {
counter = 0;
}
}, 7000);
};
Upvotes: 1
Views: 93
Reputation: 7492
Simply put the counter++
at the end of your function :
showAnime = () => {
let counter = 0;
setInterval(() => {
/* */
} else if (counter === 5) {
console.log(counter);
this.setState({
animateRightSix: "animated fadeInRightBig delay-six"
});
} else if (counter === 6) {
counter = 0;
}
counter++;
}, 7000);
};
You could heavily reduce your code by storing every sentence into an array and then picking out the current sentence out of it.
And, to automatically cycle through your sentences, you can use the modulus %
instead of setting your counter to 0 :
showAnime = () => {
let counter = 0;
setInterval(() => {
const sentences = [
"animated fadeInRightBig delay-one",
"animated fadeInRightBig delay-two",
"animated fadeInLeftBig delay-three",
"animated fadeInRightBig delay-five",
"animated fadeInRightBig delay-six"
]
this.setState({
animateRightOne: sentences[counter % 6]
});
counter++;
}, 7000);
};
Even shorter :
showAnime = () => {
let counter = 0;
setInterval(() => {
const sentences = [["one", 'Right'], ["two", 'Right'], ["three", 'Left'], ["five", 'Right'], ["six", 'Right'] ]
const [num, side] = sentences[counter % 6]
this.setState({
animateRightOne: `animated fadeIn${side}Big delay-${num}`
});
counter++;
}, 7000);
};
Upvotes: 1