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?

0

3 Answers 3

1

You are looking for setInterval:

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

Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

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); } 

1 Comment

Same as @Alexander's answer- this is blocking, and is problematic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.