I want to print some numbers using a for loop at an interval of two seconds each. The outer loop is needed in all these snippets because I need it for some other manipulation, so please don't say that there is no need for two loops.
The following code snippet waits for about 2 seconds and then prints 61 fifty times at once.
for(var i=0;i<1;i++) {
for(var j=1;j<51;j++) {
window.setInterval(function(){
console.log(10*i + j);
}, 2000);
}
}
I thought it will print 1 -- wait 2 seconds -- print 2 -- wait 2 seconds -- and so on. I thought that I am asking the browser to stop for two seconds after each iteration of the inner loop and then print the numbers. Also, I thought that the printing would stop after one iteration of the outer loop but it does not and the console keeps printing 61. One more thing, why is it printing 61?
Edit: After comments from zerkms, I now have the following code:
for(var i=0;i<1;i++) {
for(var j=1;j<51;j++) {
window.setTimeout(function(){
console.log(10*i + j);
}, 2000*j);
}
}
It prints out 50 lines at an interval of 2 seconds but it keeps printing 61 every single time. How can I print all the numbers?