Home > OS >  setTimeout is not working as expected in Reactjs
setTimeout is not working as expected in Reactjs

Time:09-16

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.

CodePudding user response:

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
    }
}
  • Related