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

105
Views
My counter stop when i switch tab (reactjs)

I am new to javascript, and I made a counter. It works, however when the tab is inactive it stops and then resumes when I return to the page. Here is my code:

import React, { useEffect, useState } from 'react'

function TimeTracker(props){

    const [time, setTime] = useState(0);
    const [timerOn, setTimerOn] = useState(false);

useEffect(()=>{

        let interval = null;

        if(timerOn){
            interval = setInterval(()=>{
                setTime(prevTime => prevTime +10)
            }, 10)

        }else{
            clearInterval(interval)

        }

        return ()=> clearInterval(interval)

    },[timerOn])
    
    return(
    <div>
    
     <p>{("0" + Math.floor((time / 60000) % 60)).slice(-2)} mn</p>
     <p>{("0" + Math.floor((time / 1000) % 60)).slice(-2)} s</p>
     <button onClick={()=>setTimerOn(true)}>Start</button>
     <button onClick={()=>setTimerOn(false)}>Stop</button>


    
    </div>
    
    
    )
}

Thank you in advance for any help you can give me.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

On most browsers inactive tabs have low priority execution and this can affect JavaScript timers.

Thus, when you not focus on your tab, interval will not work. Its not React problem.

Check this question, I wish it help you.

about 4 years ago · Juan Pablo Isaza Report

0

Your counter was not efficient

If you add a console.log before setTime and start the counter you will notice the extra renders

The code below will solve your issue:

import React, { useEffect, useState } from 'react'

function TimeTracker(props){

const [time, setTime] = useState(0);
const [timerOn, setTimerOn] = useState(false);

useEffect(()=>{

  let interval = null;
  if(timerOn){
      interval = setInterval(()=>{
          setTime(prevTime => prevTime +1)
      }, 1000)

  }else{
      clearInterval(interval)

  }

  return ()=> clearInterval(interval)

},[timerOn])

return(
<div>

 <p>0{Math.floor(time / 60)} mn</p>
 <p>{Math.floor(time % 60)} s</p>
 <button onClick={()=>setTimerOn(true)}>Start</button>
 <button onClick={()=>setTimerOn(false)}>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!