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.
Solution 1:
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)