I am using setInterval(foo, 1000);
to call a function named foo after 1 second in JavaScript.
In the function foo
i am sending api request to check something. I want to stop the setInterval
depending upon the response of api request in foo
.
Asked
Active
Viewed 743 times
0

Ahmed Ali
- 13
- 2
-
1Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – Amith Jul 23 '21 at 10:28
-
@Amith in the answer you suggested the setInterval is being cleared from outside the callback function in the global scope . I only want to know whether it can be cleared from inside the callback function – Ahmed Ali Jul 23 '21 at 10:32
-
@AhmedAli I answered your question with that constraints, please take a look and let me know if is useful. – Marco Nisi Jul 23 '21 at 10:40
1 Answers
2
As you can see here the setInterval
returns a number that can be used with clearInterval
in order to stop the interval.
If you store that number somewhere you can use it later inside your callback function.
For example:
const map = {}
const foo = () => {
// ...your async stuff goes here
clearInterval(map.interval)
}
map.interval = setInterval(foo, 1000)

Marco Nisi
- 1,211
- 10
- 13