harveen singh Kalra
harveen singh Kalra

Reputation: 11

JavaScript run a function multiple times every 4 sec

I have been working on a piece of code and I was wondering if there is a inbuilt JavaScript method which allows a function to be runned every 4 seconds for seconds and 5 times for example.

Upvotes: 0

Views: 160

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

Your question is ambiguous in the sense that it is unclear whether you want to call the function five times each interval, or call it with intervals until it has been called five times.

5 times each time interval

You can easily write a higher order function for this:

function multi_repeat(f,dmsec,times) {
    function foo() {
        setTimeout(foo,dmsec);
        for(var i = 0; i < times; i++) {
            f();
        }
    }
    setTimeout(foo,dmsec);
}

Now if your function is:

function the_alert() {
    alert("Hi");
}

You can run this with:

multi_repeat(the_alert,4000,5);

where 4000 is the number of milliseconds (so 4 seconds is 4000 milliseconds) and 5 the number of times the function should be called.

Stop after 5 calls

In case the procedure should stop after 5 calls, you can define another higher order function:

function repeat_stop(f,dmsec,times) {
    var count = 0;
    function foo() {
        f();
        count++;
        if(count < times) {
            setTimeout(foo,dmsec);
        }
    }
    setTimeout(foo,dmsec);
}

Upvotes: 2

Adrian Bratu
Adrian Bratu

Reputation: 508

you are looking at the setInverval function.

var counter = 0;
function someFunction(){
    console.log('hello world')
}

var interVal = setInterval(function(){ 
  conter++;
  if (counter < 5) {
      someFunction();
  }
  else {
      clearInterval(interVal );
  }
}, 4000);

Upvotes: 0

nvioli
nvioli

Reputation: 4219

setInterval will run a function repeatedly with a custom delay between them. To run it five times, you'll have to handle that yourself, e.g.

setInterval(function(){
  for (var i = 0; i < 5; i++){
    myFunction();
  }
},4000);

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

Upvotes: -1

Related Questions