Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Execute function every x seconds, but only execute function 3 times

I have been doing some research into this, and I came up with nothing. Basically, I am trying to write a data collection program that calls a function 3 times, waiting 10 seconds in between each call. But, all I can find is "How to call a function every x seconds for y seconds", and it doesn't solve my problem completely, since it may take more than y seconds to complete all three calls. I know I will have to use the setInterval and clearIntervals, but I don't know how I would go about formatting my loops.

like image 216
Alex Justi Avatar asked Nov 30 '22 01:11

Alex Justi


1 Answers

Use setInterval and keep a counter on each run then, clear the interval when the count gets large enough.

(function() {
  var c = 0;
  var timeout = setInterval(function() {
    //do thing
    c++;
    if (c > 2) {
      clearInterval(timeout);
    }
  }, 10000);
})();

http://codepen.io/anon/pen/bNVMQy

like image 149
j_mcnally Avatar answered Dec 06 '22 13:12

j_mcnally