I want to count from 0 to 199 three times in a row in 10 millisecond steps like 0 1 2 ... 198 199 0 1 2 .... 198 199 0 1 2 .... The first run is working fine with:
function count() {
time = 0;
for (var i = 0; i < 200; i++) {
time += 10;
setTimeout(function(j) {
return function() {
console.log(j);
}
}(i), time);
};
};
count();
but i do not get the desired result when calling the function three times like
for (var i = 0; i < 3; i++) {
count();
}
What is the right way for me?
asked Aug 12, 2014 at 19:30
Berlin_J
3871 gold badge4 silver badges16 bronze badges
2 Answers 2
I suppose that should be timed too:
for (var i = 0; i < 3; i++) {
setTimeout(animateRio /*or do you mean count?*/, i*2000);
}
answered Aug 12, 2014 at 19:33
KooiInc
124k32 gold badges145 silver badges181 bronze badges
Sign up to request clarification or add additional context in comments.
You don't need to schedule all of your own timeouts, setInterval can call a function every unit of time. So create an interval that will run every 10 milliseconds. Then add a loop counter and use some modulo arithmetic.
var time = -1,
interval,
loop = 3;
interval = setInterval(function() {
time += 1;
if(time % 200 === 0) {
loop--;
}
if(loop < 0){
clearInterval(interval);
return;
}
console.log(time % 200);
}, 10);
Comments
lang-js
animateRio();becount();?