Horje
How To Create a Delay Function in ReactJS ?

Delay functions in programming allow for pausing code­ execution, giving deve­lopers precise control over timing. These functions are essential for tasks such as content display, animations, synchronization, and managing asynchronous operations. In this article, we will discuss how can we create a delay function in ReactJs.

Pre-requisites

Steps to Create a React Application

Step 1: Create a react application by using this command

npx create-react-app <<Project-Name>>

Step 2: After creating your project folder, use the following command to navigate to it:

cd  <<Project-Name>>

Project Structure:

Approach

  • Using setTimeout method
  • Using useEffect and async/await

Approach 1: Creating a Delay Function in ReactJs Using setTimeout Method

The setTimeout function can be employed to introduce a delay before executing a certain task. In this e­xample, we’ll create­ a React component that initially displays a message­. Upon clicking a button, another message will be­ revealed afte­r waiting for one second.

Example: This example implements the above mentioned approach

Javascript

// App.js
import React, { useState } from 'react';
import './style.css'; // Import the CSS file
 
function App() {
    const [showDelayedText, setShowDelayedText] =
        useState(false);
 
    const handleClick = () => {
        setTimeout(() => {
            setShowDelayedText(true);
        }, 1000);
    };
 
    return (
        <div className="container">
            <h1 className="heading">
                Geeksforgeeks
            </h1>
            <div className="content">
                <p className="initialText">
                    This is the initial text.
                </p>
                <button className="button"
                        onClick={handleClick}>
                    Show Text
                </button>
                {showDelayedText && (
                    <p className="delayedText">
                        This text appears after a delay.
                    </p>
                )}
            </div>
        </div>
    );
}
 
export default App;

CSS

/* style.css */
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
 
.heading {
    font-size: 30px;
    margin-bottom: 10px;
    color: green;
}
 
.content {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
}
 
.initialText {
    font-size: 18px;
    color: red;
}
 
.button {
    padding: 15px;
    font-size: 16px;
    background-color: #007bff;
    color: #fff;
    border: none;
    cursor: pointer;
    border-radius: 8px;
}
 
.delayedText {
    text-align: center;
    font-size: 22px;
    color: red;
}

Step to run the application: To open the application, use the Terminal and enter the command listed below.

npm start

Output:

How-To-Create-a-Delay-Function-in-ReactJs

Approach 2: Creating a Delay Function in ReactJs Using useEffect and async/await

In this approach, a React component is create­d that initially displays a message. Whe­n a button is clicked, the component will pause­ for 2 seconds using the async/await syntax before­ revealing an additional message­.

Example: This example implements the above mentioned approach

Javascript

// App.js
import React, { useState } from 'react';
import './style.css'; // Import the CSS file
 
function App() {
    const [showDelayedText, setShowDelayedText] =
        useState(false);
 
    const delay = async (ms) => {
        return new Promise((resolve) =>
            setTimeout(resolve, ms));
    };
 
    const handleClick = async () => {
        await delay(2000);
        setShowDelayedText(true);
    };
 
    return (
        <div className="container">
            <h1 className="heading">
                Geeksforgeeks
            </h1>
            <p className="initialText">
                This is the initial text.
            </p>
            <button className="button"
                    onClick={handleClick}>
                Show Delayed Text
            </button>
            {showDelayedText && (
                <p className="delayedText">
                    This text appears after a
                    delay using async/await.
                </p>
            )}
        </div>
    );
}
 
export default App;

CSS

/* style.css */
.container {
  text-align: center;
  margin-top: 100px;
}
 
.initialText {
  font-size: 18px;
  margin-bottom: 20px;
}
 
.heading {
  font-size: 30px;
  margin-bottom: 10px;
  color: green;
}
 
.button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
  border-radius: 8px;
}
 
.delayedText {
  font-size: 22px;
  color: green;
  margin-top: 20px;
}

Output:

How-To-Create-a-Delay-Function-in-ReactJs-Example-2




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
How to Set z-index Value in React JS ? How to Set z-index Value in React JS ?
How to Create a Simple Counter App using Next.js ? How to Create a Simple Counter App using Next.js ?
How to Convert Input Value in Md5 using React JS ? How to Convert Input Value in Md5 using React JS ?
How to Disable a Button in React JS ? How to Disable a Button in React JS ?
GreenSock ScrollTrigger with React JS GreenSock ScrollTrigger with React JS

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11