I am making a simple react app, it just loads one component when it reached 100% then it loads the second one and after its 100% it loads the third one.
this is how it works, I have a start button, when you click it, it starts the first function which loads the first component:
<Button
variant="outlined"
type="submit"
onClick={() => {
setLoading(true);
start();
}}
>
Start
</Button>
and here are the loading components they are all the same expect the state is different:
const load1 = () => {
const timer = setInterval(() => {
setProgress1((prevProgress) =>
prevProgress >= 100 ? 100 : prevProgress + 10
);
}, 800);
return () => {
clearInterval(timer);
};
};
const load2 = () => {
const timer = setInterval(() => {
setProgress2((prevProgress) =>
prevProgress >= 100 ? 100 : prevProgress + 10
);
}, 800);
return () => {
clearInterval(timer);
};
};
const load3 = () => {
const timer = setInterval(() => {
setProgress3((prevProgress) =>
prevProgress >= 100 ? 100 : prevProgress + 10
);
}, 800);
return () => {
clearInterval(timer);
};
};
and my start looks like this:
const analyseDNA = () => {
setTimeout(load1, 2000);
setTimeout(setLoading2(true), 2000);
setTimeout(load2, 4000);
setTimeout(setLoading3(true), 4000);
setTimeout(load3, 6000);
};
what is supposed to happen is to load component 1 and then component 2 and then component 3 after each other. then you can press start again and it does the same.
however, with this code, component 1 and component 2 are loaded together, and then after 6 seconds component 3, when you press start again it only loads component 1, and component 3 is already loaded and nothing happens with component 2. when I open console I can see that it is printing 1, 2, 3, and it seems like the interval is never ends and it keeps going , how can I fix this?
I've made you a code sandbox. Could be prettier but it should get you on the right path. The trick would be to pass in a callback function to the load function. When the loader reaches 100 from the interval, invoke that callback which calls the next loader.
Personally, I think promises are more suitable. You would do something along the lines of creating a set interval inside a promise, then resolve the promise when the value reaches 100. This way you could make your analyseDNA function more like this:
const analyseDNA = async () => {
await load1()
await load2()
await load3()
};
Here is a sandbox for a "promise" approach. Of course, you might need to adapt if you want to show progress.