如何每秒输出一个索引中的每个数字? [英] How to output each number consecutively in an index every second?

查看:61
本文介绍了如何每秒输出一个索引中的每个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下循环:

for (let index = 0; index < 4; index++) {  
  setInterval(function() {
    console.log(index)
  }, 1000);
}

如何使控制台记录0到第一秒,1到第二秒,2到第三秒,3到第四秒,0到第五秒,依此类推,直到清除间隔?

How can I make it so that it console logs 0 the first second, 1 the second second, 2 the third second, 3 the fourth second, 0 the fifth second, and so on until the interval is cleared?

推荐答案

这是使用生成器函数的一种或多或少但更优雅的解决方案.

Here's a more-or-less-but-rather-more elegant solution using a generator function.

生成器函数在这里很有用,因为它们的执行可以通过 yield 暂停,并通过调用生成器对象的 next 方法恢复执行:

Generator functions are useful here, as their execution can be paused by yield, and resumed by calling the generator object's next method:

function* logger() {
  while (true) {
    for (let index = 0; index < 4; index++) {
      console.log(index)
      yield
    }
  }
}

let generator = logger()
setInterval(() => generator.next(), 1000)

或者,再次使用生成器,您甚至可以 yield 当前的 index ,并让interval函数记录日志(或执行其他任何操作):

Or, again with generators, you can even yield the current index, and let the interval function log (or do anything else with) it:

function* logger() {
  while (true) {
    for (let index = 0; index < 4; index++) {
      yield index
    }
  }
}

let generator = logger()
setInterval(() => console.log(generator.next().value), 1000)

这篇关于如何每秒输出一个索引中的每个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆