0

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?

3
  • 3
    Should animateRio(); be count();? Commented Aug 12, 2014 at 19:32
  • what animateRio() refers to ? Commented Aug 12, 2014 at 19:32
  • I cant find the thread that describes this correctly but I believe its because the settimeout in your count() is non-blocking so the for-loop will continue to run without the time delay. Commented Aug 12, 2014 at 19:36

2 Answers 2

2

I suppose that should be timed too:

for (var i = 0; i < 3; i++) {
  setTimeout(animateRio /*or do you mean count?*/, i*2000);
}
Sign up to request clarification or add additional context in comments.

3 Comments

i mean "count". Sorry! I will try the nested timeout.
it is not working. the console gives each number from 0 to 199 three times at the same time
now it is working fine. i used "count()" instead of just "count". Thank you very much!
0

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

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.