I have the following code in Javacript (React):
useEffect(() => {
const timer1 = setTimeout(() => {
// task 1
}, 1000)
const timer2 = setTimeout(() => {
// task 2
}, 2000)
const timer3 = setTimeout(() => {
// task 3
}, 3000)
// returns to the first task and starts all over again
return () => {
clearTimeout(timer1)
clearTimeout(timer2)
clearTimeout(timer3)
}
}, [])
my question is: how to make it so that as soon as all the timeouts are executed until the last one, I call them to be executed all over again? I simply need to run this sequence of timeouts multiple times.
I tried to throw all the setTimeouts in a function and call them in the useEffect, but I can’t clear the timeouts correctly inside the hook.
Flow example:
- 1 second later: timer1 executes task 1
- +1 second later: timer2 runs task 2
- +1 second later: timer3 runs task 3
- restarts the flow from the beginning, from timer1.
3
Answers
You can clear the interval duration once the 3rd timeout completes it’s cycle.
For ex:
Let me give you an idea. All you need is to re-run the
useEffect
once your last timer is completed.You can have a state which can be modified at last and pass it as dependency to the
useEffect
.You can use setInterval() method to create a sort of loop. It would look like this: