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

108
Views
Avoid setInterval from being Cleared

I have a simple Clock component on my Website, code is given below :

import { useEffect, useState } from 'react'

const Clock = () => {
  const [time, setTime] = useState()

  useEffect(() => {

    setInterval(() => {
      const dateObject = new Date() //` Date Object
      var currentTime = dateObject.getHours() + ' : ' + dateObject.getMinutes()

      setTime(currentTime)

    }, 1000)

  }, [])

  return <div>{time}</div>
}

export default Clock

But on some other page I have am running a loop to clear timeouts on that specific page, But what end up happening is my clock interval also get cleared. (It is very important to clear timeouts on that page for my desired functionality, this clears out any timeouts currently running.)
Code for which is :

const highestId = window.setTimeout(() => {
  for (let i = highestId; i >= 0; i--) {
    window.clearTimeout(i)
  }
}, 0)

I want to keep clock interval running but also cancel all other ones.

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

0

You can keep a track of either setTimeout IDs or setInterval IDs and then clear just the timeout IDs.

/* Make sure the timeoutIDs doesn't get reinitialised everytime you run this code, 
probably store it some central service that remains in memory, or declare it globally
*/
const timeoutIDs = [];
const id = window.setTimeout(() => {
  for (let i = 0; i < timeoutIDs.length; i++) {
    window.clearTimeout(timeoutIDs[i])
  }
}, 0);
timeoutIDs.push(id)

OR :

import { useEffect, useState } from 'react'

export const IntervalSet = new Set();

const Clock = () => {
  const [time, setTime] = useState()

  useEffect(() => {

    const id = setInterval(() => {
      const dateObject = new Date() //` Date Object
      var currentTime = dateObject.getHours() + ' : ' + dateObject.getMinutes()

      setTime(currentTime)

    }, 1000)
    
    set.add(id);

  }, [])

  return <div>{time}</div>
}

export default Clock;

import { IntervalSet } from 'somePath'; 

const highestId = window.setTimeout(() => {
  for (let i = highestId; i >= 0; i--) {
    if(IntervalSet.has(i)) {
      continue;
    }
    window.clearTimeout(i)
  }
}, 0)
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!