Wednesday, 23 August 2017

loops - Print to console values between to integers infinitely in JavaScript




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?


Answer



You are looking for setInterval:






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





No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...