What is the most recommended/best way to stop multiple instances of a setInterval function from being created (in javascript) and call it only once?
Asked
Active
Viewed 635 times
-1
-
Only one instance of the `setInterval()` function exists. Your question does not make any sense without details about the problem you are experiencing. – Pointy Jan 08 '21 at 17:27
-
Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – stealththeninja Jan 08 '21 at 17:32
1 Answers
2
setInterval
returns an interval id you can use to check to see if it's already been instantiated. For example:
let intervalId
const someFunction = () => {
intervalId = setInterval(someOtherFunction, 1000)
}
const someThirdFunction () => {
if (!intervalId) {
intervalId = setInterval(someOtherFunction, 1000)
}
}

Zac Anger
- 6,983
- 2
- 15
- 42
-
Thanks for the answer... Will this prevent multiple instances of setInterval if I have a post request that contains a setInterval and when I call it, it generates multiple every time I send a post request? – ddark13 Jan 08 '21 at 17:51
-
1As long as you don't have anything else calling `clearInterval(intervalId)`, then yeah, no new intervals will be created. – Zac Anger Jan 08 '21 at 17:53
-
Hmm it still making multiple instance... I think when I call post request more then once it creates Setinterval separate times... IS there a way to prevent that? – ddark13 Jan 08 '21 at 18:07
-
1Are you checking in the post function handler for if `intervalId` has been initialized? Can you post that code? – Zac Anger Jan 08 '21 at 18:10
-
something like this `router.post("/", (req, res) => { function myFn() {console.log(q += 1);} let intervalId; let someFunction = () => { intervalId = setInterval(myFn, 2000) if(!intervalId){ clearInterval(); } } someFunction(); res.send('Success'); }) ` – ddark13 Jan 08 '21 at 18:21
-
1This looks a little mixed up. `clearInterval` takes an intervalId, and I assume `q` is defined above the function. Because `someFunction` and `intervalId` are being initialized and defined in the callback to router.post, yes, they would be recreated on each post. They should be lifted out of the callback if the goal is to only have one unique interval timer per the process, rather than per request. – Zac Anger Jan 08 '21 at 18:30
-
I see, so I would have to create "somefunction" outside the post and then call it in the post somefunction() – ddark13 Jan 08 '21 at 18:39
-
The `let intervalId` specifically needs to be outside of the post callback, but you can also lift anything else outside of there unless it needs to access the scope within that callback. Maybe it would be more clear if you explained what you're trying to do, is this a counter for request times or something? – Zac Anger Jan 08 '21 at 18:45