How to output each number consecutively in an index every second?

让人想犯罪 __ 提交于 2021-01-16 04:11:10

问题


I have the following loop:

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

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?


回答1:


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

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)

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)



回答2:


var counter = 0,
  limit = 5,
  handle; // global vars

function start() {
  counter = 0;
  clearInterval(handle); // reset
  handle = setInterval(count, 1000); // interval handle
}

function count() {
  console.log(counter++); // increment counter
  if (counter >= limit) { // check limit
    clearInterval(handle); //  stop timer
  }
}

function stop() {
  clearInterval(handle);
}

start();

setTimeout(function(){
start();
},3110); // reset while counting.

As mentioned in the comments added reset functionality.



来源:https://stackoverflow.com/questions/59220387/how-to-output-each-number-consecutively-in-an-index-every-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!