如何正确设置Interval Generator?

时间:2018-01-13 15:25:52

标签: javascript generator setinterval

目标: 我想创建一个在.subscribe(m => {this.currentMemberDetail = m; console.log(this.currentMemberDetail)}); 内调用的生成器函数,以及setInterval() 1到10。

问题: 为了console.log最后我需要一个条件来检查是否clearInterval()。 但每次条件运行时,它会调用另一个gen.next().done === true 所以我得到的最终印刷品是: .next()

如何在不致电1 3 5 7 9 undefined的情况下设置 done == true condition

.next()

5 个答案:

答案 0 :(得分:5)

你记住变量中的对象,而不是第二次调用next

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)

答案 1 :(得分:1)

您也可以使用for..of循环,setTimeout()async/await来避免检查.done属性值

&#13;
&#13;
function* myGen() {
  let counter = 0;
  for (let i = 0; i <= 10; i++) {
    yield counter++;
  }
}

const gen = myGen();

(async() => {
  for (let n of gen) {
    await new Promise(resolve => {
      setTimeout(() => {
        console.log(n);
        resolve()
      }, 1500)
    })
  }
})();
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需存储nextValue

function* myGen(){
    let counter = 0;
    for(let i = 0 ; i <= 10; i++){
        yield counter++;    
    }
}

const gen = myGen();
const start = setInterval(() => {
    let nextValue = gen.next();
    if(nextValue.done){
        clearInterval(start);
    } else {
        console.log(nextValue.value);  
    }
}, 1500)

答案 3 :(得分:0)

function* myGen(){
let counter = 0;
for(let i = 0 ; i <= 10; i++){
    yield counter++;    
}
}

const gen = myGen();
const start = setInterval(() => {
var genObj=gen.next();//keep next result as an object to avoid use next method twice

if(genObj.done){
    clearInterval(start);
} else {
    console.log(genObj.value);  
}
}, 1500)//I spent an hour learning this,late but get some konwledge,so,thanks.

答案 4 :(得分:0)

另一种方法是使用相对较新的AsyncGenerator功能
https://github.com/tc39/proposal-async-iteration

我认为它很好地抽象了问题(创建一个在每次迭代之间休眠的迭代器)。

async function* sleepGenerator(numSleeps, sleepMillis) {
    for (let i = 0; i < numSleeps; i++) {
        await sleep(sleepMillis);
        yield {i, numSleeps, sleepMillis};
    }
}

function sleep(sleepMillis) {
    return new Promise(resolve => setTimeout(resolve, sleepMillis));
}

(async function run() {
    for await (const iterMeta of sleepGenerator(5, 500)) {
        console.log(iterMeta);
    }
})();