Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

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

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?

Upvotes: 2

Views: 370

Answers (2)

FZs
FZs

Reputation: 18609

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)

Upvotes: 6

Eldar
Eldar

Reputation: 10790

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.

Upvotes: 1

Related Questions