-1

I've an function and a conditional in that function and I will create loop by 4 times and break without without thinking any conditional.

Here is my idea

    function test (){

       var i = 0;

       $.ajax({
           setup:,
           success:function(data){
            if(data.resp ==true){
               if(i<= 4){
                test();
                 break;
                  return false;
               }
               }else{
               success;
               }
            }
       })
i++;
    }

I know this function will not work but I don't know how to do

DMS-KH
  • 2,669
  • 8
  • 43
  • 73

2 Answers2

1

To call it recursively keeping i local, you could use:

(function test(i) {
  $.ajax({
    url: 'uriThere.com',
    success: function(data) {
      if (i < 4 && data.resp == true) {
        test(++i);
      }
    }
  });
})(0);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

Either make the var i = 0 variable outside of the function or try

function test (varI){

   var i = varI;

   $.ajax({
       setup:,
       success:function(data){
        if(data.resp ==true){
           if(i<= 4){
               test(++i);
               return false;
           }else{
               success;
           }
        }
    })
    i++;
}
  • This is wrong: `test(i++)` must be `test(++i)` and remove `i++;` – A. Wolff Dec 11 '15 at 10:08
  • @A.Wolff what is difference betwen ++i and i++? – DMS-KH Dec 11 '15 at 10:09
  • @HengSopheak http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i In this answer, this works because extra `i++` and end of test() method, but what happen is that using `test(i++)` you pass value of `i` before it is incremented, while using `test(++i)` you pas incremanted value. – A. Wolff Dec 11 '15 at 10:10
  • @A.Wolff Thanks. Missed that. So used to incrementing in for loops :P –  Dec 11 '15 at 10:17