J.DOOOOOE
J.DOOOOOE

Reputation: 1

Iterating a function over again after each iteration finishes

I am struggling to code a way for a function to iterate multiple times with a 5 second pause between each iteration. Each iteration needs to be finished before the next iteration starts.

I have been told that Callback functions or Promises would be the way to go but I am very new to Javascript and am having trouble coding it.

Would anyone be able to help me out? Let's just say the function in question is called "Ineedhelp()"

Thanks

Upvotes: 0

Views: 76

Answers (2)

scorgn
scorgn

Reputation: 3629

One good way to do this would put a timeout at the end of your function. For example, if you want it to iterate 5 times the following code would work.

var i = 0;
function iNeedHelp() {
    i++;
    alert('You\'ve been helped ' + i + ' times so far.');
    if (i < 5) {
    setTimeout(function(){iNeedHelp()}, 5000);
  }
}
iNeedHelp();

Upvotes: 1

Mark Madej
Mark Madej

Reputation: 1912

There are a bunch of ways to do this, but one simple way is using setInterval / clearInterval:

var maxIterations = 3;
var iterations = 0;
var msDelay = 5000;
iNeedHelp();
var interval = setInterval(iNeedHelp, msDelay);
function iNeedHelp() {
    iterations++;
    console.log("in iNeedHelp, iteration " + iterations);
    if (iterations >= maxIterations) {
        clearInterval(interval);
    }
}

This will run iNeedHelp as many times as is set in maxIteration, with a pause of msDelay milliseconds in between each call.

You can find some additional info on setInterval/clearInterval here : https://www.w3schools.com/jsref/met_win_setinterval.asp

Upvotes: 0

Related Questions