Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setInterval Generator correctly?

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)
like image 977
ueeieiie Avatar asked Dec 11 '22 08:12

ueeieiie


1 Answers

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)
like image 117
T.J. Crowder Avatar answered Dec 19 '22 09:12

T.J. Crowder