Goal:
I want to create a generator function that is being invoked inside setInterval()
, and console.log
1 to 10.
the problem:
In order to clearInterval()
at the end I need a condition to check if gen.next().done === true
.
but every time the condition runs it actualy calls another .next()
so so final print i get is:
1 3 5 7 9 undefined
How do I set a done == true condition without calling .next()
?
function* myGen(){
let counter = 0;
for(let i = 0 ; i <= 10; i++){
yield counter++;
}
}
const gen = myGen();
const start = setInterval(() => {
if(gen.next().done){
clearInterval(start);
} else {
console.log(gen.next().value);
}
}, 1500)