0

I have a script that looks similar to the following:

function1() {
    for(i < 5) {
        function2(i);
    }
}

function2(i) {
    $jqueryHere;
}

Basically, I have a for loop which calls the second function a certain number of times. However, the second function contains only jQuery and I don't know how to force the for loop to wait for the execution of function2() to be finished before moving on and going to the next iteration and increasing the variable i.

EDIT: Here is the specific jQuery code in second function (I'm using typed.js to write lines out on my site):

function type(n, text, print) {
  $('#line' + (n + 1)).typed({
      strings: text[i],
      typeSpeed: 3,
      backDelay: 500,
      loop: false,
      contentType: 'html',
      loopCount: false,
      callback: function() {
        $('#line' + (n + 1)).siblings('.typed-cursor').remove();
        $(print[n]).insertAfter('#line' + (n + 1));
      }
  });

  $(".reset").click(function(){
      $('#line' + (n + 1)).typed('reset');
  });
}
jswny
  • 167
  • 1
  • 12
  • provide your ajax code – AsgarAli Feb 02 '16 at 18:12
  • Do you want it to wait for the ajax call to finish? If so, you could throw `async: false` in your ajax call to force it to be synchronous. Ideally, you would leave it async and your app would handle it correctly but without more code it's difficult to tell what you are doing. – Matt Feb 02 '16 at 18:16
  • I've just added my code for the second function. – jswny Feb 02 '16 at 18:28

1 Answers1

0

EDIT: I would recommend just using promises instead, and call then() five times, but if you want to be able to adjust the number of times you want to call the async function, you need to track the iteration count between the async calls. You can do this by storing the number of calls you have made in an external scope, or you can do it as I've done below by passing it as a parameter.

function f1(i) { 
  if (!i || i < 5) // nullguard the parameter so function can be called as 'f1()'
    f2(i || 0);
}

function f2(i) {
  $ajax.onComplete = function () { f1(i+1); }
  $doAjax();
}

An example of storing the counter in an external scope would be the following:

(function () {
  var count = 0;

  function f1() {
    if (count < 5) 
      f2();
  }

  function f2() {
    $ajax.onComplete = function () { count++; f1(); }
    $doAjax();
  }
})()
Cameron
  • 434
  • 2
  • 4
  • Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See [answer] for more information. – Heretic Monkey Feb 02 '16 at 18:18