How to make a delay in React

Viewed 373

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

3 Answers

I believe you are using the useReducer hook. You can do the dispatch inside the callback of setInterval. You need to carefully handle the memory leaks as well.

Try like this:

  1. Add the following hooks to your component. trigger is to trigger the screen transitions. We call setInterval only once (using if check) to avoid memory leaks and clear it when the component unmounts.
  const [trigger, setTrigger] = useState(false);

  useEffect(() => {
    let interval;
    if (trigger) {
      interval = setInterval(() => dispatch({ type: "NEXT_SCREEN" }), 3000);
    }
    return () => clearInterval(interval);
  }, [trigger]);
  1. Change the trigger to true when the button click happens
<button
  className="button _button_two_column"
  onClick={() => setTrigger(true)}
></button>

Demo code:

Edit priceless-wu-ulodn1

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

The solution to my task:

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