0

I would like to console.log values between 1 and 5 infinitely with a small delay of few seconds using JavaScript. I am trying to run the following code, but it stops after printing 1.

    var z = 0
    setTimeout(function() { 
      if (z==6) {z=0};
        z+=1;
        console.log(z);
    }, 2000);

Is it possible to implement this using setTimeout function?

Derek Brown
  • 4,232
  • 4
  • 27
  • 44
Dmitry Rastorguev
  • 3,473
  • 4
  • 13
  • 14

3 Answers3

1

You are looking for setInterval:

var z=0; 
setInterval(function() { 
  if (z==6) {z=0};
  z+=1;
  console.log(z);
}, 2000);
Derek Brown
  • 4,232
  • 4
  • 27
  • 44
Osama
  • 2,912
  • 1
  • 12
  • 15
0

setTimeout() just performs the function once. you need use setInterval().:

var z=0; 
setInterval(function() { 
if (z==6) {z=0};
z+=1;
console.log(z);
}, 2000);
0

Here's a potential solution. It's not implemented "infinitely" so the browser doesn't die, but you could increase i to your liking I suppose.

for (let i = 0; i < 100; i++) {
    setTimeout(function() {
    console.log(i % 5 + 1);
  }, 2000 * i);
}
Nick
  • 16,066
  • 3
  • 16
  • 32