How to countdown in react js (Javascript Scripting Language)

Asked by: Tomiko Rey
Edit Question Icon
Edit
Follow Icon
Report Icon
Report

Explain Below What Do You Want to report!


Available Answers: 1

Shribhagwan Korde (PHYSICIAN ASSISTANT Call Center, Higher Education, Sas, Fda) From: Lucknow/India
1
import React from 'react'
2
import { useState, useEffect } from 'react';
3
const Timer = (props:any) => {
4
    const {initialMinute = 0,initialSeconds = 0} = props;
5
    const [ minutes, setMinutes ] = useState(initialMinute);
6
    const [seconds, setSeconds ] =  useState(initialSeconds);
7
    useEffect(()=>{
8
    let myInterval = setInterval(() => {
9
            if (seconds > 0) {
10
                setSeconds(seconds - 1);
11
            }
12
            if (seconds === 0) {
13
                if (minutes === 0) {
14
                    clearInterval(myInterval)
15
                } else {
16
                    setMinutes(minutes - 1);
17
                    setSeconds(59);
18
                }
19
            } 
20
        }, 1000)
21
        return ()=> {
22
            clearInterval(myInterval);
23
          };
24
    });
25
    return (
26
        <div>
27
        { minutes === 0 && seconds === 0
28
            ? null
29
            : <h1> {minutes}:{seconds < 10 ?  `0${seconds}` : seconds}</h1> 
30
        }
31
        </div>
32
    )
33
}
34
export default Timer;
Upvote Icon10
Comment IconComment
Follow Icon
Report IconReport

Explain Below What Do You Want to report!


Explain Below What Do You Want to comment!




More Questions



Would you like to join Ask Sawal!

Why?

  1. Ask Sawal is a fast growing question and answer discussion forum.

  2. 15 lakh+ questions were answered by our Ask Sawal Members.

  3. Each day 1000s of questions asked & 1000s of questions answered.

  4. Ask any question and get answer from 2.5 Lakh+ Ask Sawal Members.

  5. Constant moderation and reporting option makes questions and answers spam free.

  6. And also, we have free blogging platform. Write an article on any topic.

  7. We have 10000+ visitors each day. So a beneficial platform for link building.

  8. We are allowing link sharing. Create backlinks to your blog site or any site.

  9. Gain extra passive income by sharing your affiliate links in articles and answers.