Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add delay in Reactjs

I am new to Reactjs. I am not sure how to add delay to render in Reactjs.What is the best way to add delay.

I am adding the following code in render but its not working.

setTimeout(function() {  }, 1000); 
like image 343
shubham agrawal Avatar asked Feb 07 '17 12:02

shubham agrawal


People also ask

How do you add a delay?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

What is delay () in Javascript?

Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.

How do you wait for state change in React?

Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.


2 Answers

Not sure why you would want to do this, but something like this?

The component's constructor:

constructor(props) {     super(props);     this.state = {         render: false //Set render state to false     } } 

On component mount:

componentDidMount() {   setTimeout(function() { //Start the timer       this.setState({render: true}) //After 1 second, set render to true   }.bind(this), 1000) } 

The render method:

render() {     let renderContainer = false //By default don't render anything     if(this.state.render) { //If this.state.render == true, which is set to true by the timer.         renderContainer = <div>Look at me! I'm content!</div> //Add dom elements     }     return (       renderContainer //Render the dom elements, or, when this.state == false, nothing.     )   } 

So when the timer fires, render is set to true. Because render is stored in state, this also triggers a re-render of the component. The if statement simply instructs renderContainer to not display anything unless the state render is true. You could also show a text indicating the component is loading, by instead of declaring renderContainer= false at the top, declaring the default as renderContainer=<div>Component is loading..</div> for example.

like image 160
Rob van Dijk Avatar answered Sep 19 '22 22:09

Rob van Dijk


Pure typescript Solution

You would be able to create delay function with async

function timeout(delay: number) {     return new Promise( res => setTimeout(res, delay) ); } 

and then call the function

await timeout(1000); //for 1 sec delay 
like image 32
Ronit Roy Avatar answered Sep 18 '22 22:09

Ronit Roy