Skip to content
Advertisement

Getting problem in making a timer/ count-down code in ReactJs

I am getting a problem in making a countdown timer which will start on clicking on start button and it will stop onClicking on the stop button. I have made that thing on javascript but when I came to reactJs, I am getting unable. I am providing all the codes. And please check what is the problem.

JavaScript

Advertisement

Answer

Issues

  1. The timer/interval reference is redeclared each render cycle, so you can never clear it once anything causes the component to rerender.
  2. You’ve a stale enclosure of the data state value in the interval callback.

Solution

  1. Use a React ref to hold the interval reference.
  2. Use a functional state update to correctly update the data counter.

Code

JavaScript

Demo

Edit getting-problem-in-making-a-timer-count-down-code-in-reactjs

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement