Home > Blockchain >  How to make a delay in React
How to make a delay in React

Time:05-23

When you click on the button, another screen is rendered:

<button className="button _button_two_column" onClick={()=> dispatch({type: "NEXT_SCREEN"})}>
if (action.type === 'NEXT_SCREEN') {
        return {
            ...state,
            currentScreenIndex: state.currentScreenIndex   1,
        }
    }

/when 1 is added to the currentScreenIndex the screen changes/

I need screen 1 to open for 3 seconds when I press the button and then screen 2 How to do it? I tried to do it using setTimeout, but nothing happened

CodePudding user response:

I believe you are using the Edit priceless-wu-ulodn1

CodePudding user response:

I suggest to use setTimeout() function to make a delay. And avoid to use javascript function in html.

const onClick = () => {
    setTimeout(dispatch({type: "NEXT_SCREEN"}), 1000)
}
<button className="button _button_two_column" onClick={onClick}>

CodePudding user response:

The solution to my task:

useEffect(() => {
  let interval;
  if (stateScreen.currentScreenIndex===4) {
    interval = setInterval(() => dispatch({ type: "NEXT_SCREEN" }), 2000);
  }
  return () => clearInterval(interval);
}, );
  • Related