Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
React.js, implementing timer, getting weird behaviour

I am trying to create a simple timer with React, where start button starts the timer, and stop button pauses it. However this gives some unexpected behavior.

First click on start, the timer changes to 1 and pauses, on second click it oscillates between 1 and 2. Unable to understand why this is happening. Any help would be greatly appreciated!

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [time, setTime] = useState(0)
  let t;
  function startTime(){
    t = setInterval(()=>{
      setTime(time+1);
    },1000)
  }
  function stopTime(){
    clearInterval(t);
  }
  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startTime}>Start</button>
      <button onClick={stopTime}>Stop</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As you did, on first click you create a function in memory that will call setTime(0+1) for ever, as 0 is the value of time when you registered that function in memory. To have the updated time, you would wanna pass a function to setTime.

Also, to memoize the interval reference, you should be using a React ref, as a normal variable will come to its initial value at each render. Here is a working example on CodeSandbox and the code below:

import { useState, useRef } from "react";
import "./styles.css";

export default function App() {
  const [time, setTime] = useState(0)
  const timerRef = useRef();
  function startTime(){
    timerRef.current = setInterval(()=>{
      setTime(time =>time+1);
    },1000)
  }
  function stopTime(){
    clearInterval(timerRef.current);
  }

  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startTime}>Start</button>
      <button onClick={stopTime}>Stop</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!