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)
You remember the object in a variable rather than calling next
a second time:
function* myGen(){
let counter = 0;
for(let i = 0 ; i <= 10; i++){
yield counter++;
}
}
const gen = myGen();
const start = setInterval(() => {
var next = gen.next(); // *** Save it here
if(next.done){ // *** Use it here...
clearInterval(start);
} else {
console.log(next.value); // *** ...and here
}
}, 150)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With