How we can clear the setInterval after the 10 times it print the consoled value.
I have tried a way with simple JS code but I am expecting better answer than what i tried.
my code is given below..
let c = 0;
let datainter = setInterval(() => {
c += 1;
console.log(c);
if(c == 10) {
inter();
}
}, 1000)
function inter() {
clearInterval(datainter);
console.log('interval ended')
}
2
Answers
An alternative could be
setTimeout
without clearing anything:You could use recursion with a call to
setTimeout
.If you want to check if the loop is finished, just wrap it in a promise and call
resolve
.Alternatively, you could create options and have a callback: