The animation of react-circular-progressbar is experiencing a slight delay of one second

I managed to create a circular progress bar with a timer and a button that adds +10 seconds to the timer.

However, I'm facing a 1-second delay in the animation of the progress bar when clicking on the button.

If anyone could assist me in resolving this issue, I would greatly appreciate it.

You can view the sandbox link here: https://codesandbox.io/s/quirky-monad-rc8ir3?file=/src/App.js

import React from "react";
import styles from "./circle.module.css";

import { useState, useEffect } from "react";

import image from "./image2.png"


import { CircularProgressbar, buildStyles } from "react-circular-progressbar";
import "react-circular-progressbar/dist/styles.css";

export default function Circle() {
  const [min, setMin] = useState(0);
  const [sec, setSec] = useState(35);
  const [amount, setAmount] = useState(1.5);
  const [progress, setProgress] = useState(0);
  const [start, setStart] = useState(true);


  useEffect(() => {
      let x = sec,
        y = min;

    const interval = setInterval(() => {
      if ((x === 0 && y === 0) || start === false) {
        setStart(false);
        return;
      }
      console.log(x, y, y + x / 60);

      if (x < 1) {
        setSec(59);
        setMin(y - 1);
      } else if (x < 60) {
        --x;
        setSec(x);
      }
      setProgress((y + x / 60) / amount);
      console.log(progress);
    }, 1000);

    return () => {
        
      clearInterval(interval);
    };
  }, [sec, start, progress]);

  const increase = () => {
    if (start === false) {
      setStart(true);
    }
    if (sec + 10 > 59) {
      setMin(min + 1);
      setSec(sec + 10 - 60);
    } else {
      setSec(sec + 10);
    }
  };

  return (
    <>
      <div className={styles.whole}>
        <h2>Routine Starting in...</h2>
        <p>sub heading here</p>
        <CircularProgressbar
          className={styles.progress}
          value={progress}
          maxValue={1}
          text={
            (min < 10 ? `0${min}` : min) + ":" + (sec < 10 ? `0${sec}` : sec)
          }
          styles={buildStyles({
            pathTransitionDuration: 0.2,
            trailColor: "#d6d6d6",
            pathColor: `rgba(108,62,119,255)`,
            textColor: "#2e2e2e",
          })}
        />
      </div>

      <div className={styles.btn}>
        <button  onClick={increase}>
        <b>+10 sec</b> 
        </button>


        <button  >
         <b> skip</b> 
        </button>
      </div>

      <div className={styles.steps}>
        
          <b>Steps 2/3</b> 
        
        <img src={image}/>
        <h2>Cleansing</h2>
      </div>
    </>
  );
}

I am aiming to synchronize the timer and progress bar correctly when pressing the +10 second increase button.

Here is the sandbox link for reference: https://codesandbox.io/s/quirky-monad-rc8ir3?file=/src/App.js

Answer №1

For optimal functionality, ensure to call setProgress within the useEffect hook as well as in the increase function:

  useEffect(() => {
    let seconds = sec,
      minutes = min;

    setProgress((minutes + seconds / 60) / amount);

    const interval = setInterval(() => {
      if ((seconds === 0 && minutes === 0) || start === false) {
        setStart(false);
        return;
      }

      if (seconds < 1) {
        setSec(59);
        setMin(minutes - 1);
      } else if (seconds < 60) {
        --seconds;
        setSec(seconds);
      }

      setProgress((minutes + seconds / 60) / amount);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [sec, start, progress]);

  const increase = () => {
    let seconds = sec,
      minutes = min;

    if (start === false) {
      setStart(true);
    }
    if (sec + 10 > 59) {
      minutes = min + 1;
      seconds = sec + 10 - 60;
      setMin(minutes);
      setSec(seconds);
    } else {
      seconds = sec + 10;
      setSec(seconds);
    }

    setProgress((minutes + seconds / 60) / amount);
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Click on the button to automatically scroll to a specific component inside the dialog

In my JSF/Primefaces application, I have a page with a long content that can be scrolled, along with a dialog also containing lengthy content that requires scrolling. The dialog includes a button and I am looking to scroll the dialog content to a specific ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

The regular expression pattern ((xn--)?[a-z0-9]+(-[a-z0-9]+)*.)+[a-z]{2,} is functional when used on regexpal.com, however, it does not yield the

Within the code snippet below, the regular expression in the "pattern" variable is specifically designed to only match the criteria mentioned in the comment (which requires a minimum of 1 letter followed by a dot, and then two letters). var link = "Help" ...

What is the best way to execute a specific set of unit tests in Gulp-Angular using Karma?

In the midst of my AngularJS 1.4 project, fashioned through the Gulp-Angular yeoman generator, I find myself facing a dilemma. With karma and gulp settings already in place, executing gulp test runs all *.spec.js files within the project. However, my desir ...

Leverage the JSON data to populate the category axis in c3.js

I have a JSON object that contains an array called datas, which holds the data I need to use for my chart. I want to utilize the data1 array for the x-axis in a category format. How can I achieve this? This is my attempted solution, where I extract the da ...

GAE does not have access to background images

Having trouble loading background pictures in my GAE front-end app. "Failed to load resource: the server responded with a status of 404 (Not Found)". My app is a simple website, no GAE backend. Using Eclipse with Google AppEngine Plugin. Background pict ...

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

What is causing the color to be replaced by the latest selection?

I'm having trouble drawing three lines with different colors. They all end up being the same color, which is the last color specified in my code snippet below: function initObject() { var lineLength = 10; geometry = new THREE.Geometry ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

After pushing my code to Heroku, I encountered a MongoNetworkError that prevented my app from connecting to the MongoDB database

I have developed a full stack Shopping List App (essentially similar to a To Do List) using mongoDB, Express, React, and Node. The application functions perfectly in my local environment. However, upon attempting to deploy the App on Heroku, I encountered ...

What is the best way to transfer a UserID from State to a GET URL?

I have my userInfo saved in a state variable const [users, setUsers] = useState([]) I need help passing the userId into the axios URL to fetch posts of a specific user. Here's what I have tried. I know it's not correct, so please assist me. Das ...

Is the Messenger Bot ignoring random users?

I am facing an issue that I need help explaining. The bot works perfectly when I use it from my own Facebook account. However, when I ask others to use it, the bot does not respond to them, even though I have received a green tick on the pages_messaging a ...

Error: The function req.logIn is not valid

I'm currently in the process of creating a dashboard for my Discord bot, but I've encountered an error that reads as follows: TypeError: req.logIn is not a function at Strategy.strategy.success (C:\Users\joasb\Desktop\Bot& ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

Assign a value to a hash object based on a specific location stored within an array

I'm struggling to figure out how to retrieve the original JSON data when its structure is variable. var jsonData = { "parent": { "child": "foo" } }; fu ...

Unable to modify the state within the header of a Material Table while utilizing remote data sources

My custom header contains a simple boolean state that I plan to use to control a dropdown menu. I have implemented an onClick function on this custom header to toggle the state and then log it, but the state remains unchanged after each click. The issue a ...

Exploring deep nested components and elements in Angular for a targeted specific functionality

Is it possible to apply the ng deep css class to only one specific checkbox in my component, rather than all checkboxes? I want to customize just one checkbox and leave the others unchanged. How can this be achieved? Thank you. I need the CSS modificatio ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...

Generating option list from API JSON responses

I am currently developing a news app using React. I have set up my API to fetch data from newsapi.org and my goal is to display the available news source options in a dropdown list within my select component. However, instead of listing all news sources w ...