Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setTimeout is not working as expected in Reactjs

I am trying to animate six blocks, as they are transformed to scale(0) so that they are not visible at the moment. When a button is clicked Animate function runs and while looping it changes/updates the state

let [scale, setScale] = useState({prop1: 'scale(0)',
        prop2: 'scale(0)',
        prop3: 'scale(0)',
        prop4: 'scale(0)',
        prop5: 'scale(0)',
        prop6: 'scale(0)'})

const animate = () => {
    for (let i = 1; i <= 6; i ++){
        setTimeout(() => {
            let key = `prop${i}`;
            setScale(prev => ({...prev, [key]: 'scale(1)'}));
        }, 500)
    }
}

as the setScale changes the state, the UI component is updated. According to this function, what I want to do is at every loop I want to set a timeout after which the setScale function should execute, but that’s not how it is executed. All the six blocks are rendered at once and not one by one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your setTimeout is being executed once for each iteration of your for loop. That means that each update all executes almost at the same time. So after 500ms all updates happen at once.

const animate = () => {
    let startTime = 500;

    for (let i = 1; i <= 6; i ++){
        setTimeout(() => {
            let key = `prop${i}`;
            setScale(prev => ({...prev, [key]: 'scale(1)'}));
        }, startTime)
        startTime += 500; #increment the time so each change is half a second from the original
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading