2

I thought this questions must have been asked before, but i couldnt find another thread for this. Anyways I want to repeat a function 20 times, and half a second between each time.

  for (var i = 0; i < 20; i++)
     {
            setTimeout(function(){  
                   mySwiper.update();
                   console.log("Test");}, 500);

     }

But at the moment it just wait for half a second, then repeat itself 20 times in 1 go. Not sure how to do it. Thanks for your time

John
  • 983
  • 1
  • 13
  • 31

3 Answers3

3

It's a bit of hack, but you can multiply the interval by the index to give it the same effect.

for (var i = 0; i < 20; i++) {
    setTimeout(function() {
        mySwiper.update();
        console.log("Test");
    }, 500 * i);
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
3

The problem you're facing is because setTimeout (and setInterval) works on another thread. Your look finishes is an instant, so essentially all your timers are started at the same time. What you want to do is chain them together recursively, so that each timer calls the next one, and keeps the count.

function count(num){
    setTimeout(function(){  
        mySwiper.update();
        console.log("Test");
        if(num > 0) count(num - 1);
    }, 500);
}

Then, instead of a loop, you'd just do

count(20);

As a note, if you want it to fire every half a second no matter how long everything else takes, move use what @Arun suggested. My method makes it take another 500ms after everything is finished.

David
  • 4,744
  • 5
  • 33
  • 64
1

If you look at how you have used setTimeout, you are calling setTimeout 20 times with the delay as 500 which means after 500ms the passed function will be executed 20 times one by each call to setTimeout().

One solution is to use a counter and setInterval()

var counter = 0,
    interval = setInterval(function () {
        mySwiper.update();
        if (++counter == 20) {
            clearInterval(interval);
        }
    })
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531