0

Trying to postpone further processing of script until ajax call is complete without using the callback. Trying something like this, but it locks. How do I do this without locking?

var loaded=false;
$.get(url,function(d){loaded=true;});

while(!loaded)  //<--locks here
  setTimeout(void(0),100);

//continue script after ajax call is complete
RealWorldCoder
  • 1,031
  • 1
  • 10
  • 16
  • 1
    The purpose of callbacks is to avoid locking. Surely there's a way to do it using callbacks ? – Rosh Donniet May 20 '16 at 07:25
  • Ask yourself _"Why"_ than _"How"_... – Rayon May 20 '16 at 07:26
  • 1
    this ques might help u http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – bob May 20 '16 at 07:27
  • Well, sometimes is better to write your problem as more detailed as you can and with a possible solution but let the users find a better way to write your code. This timeout in while seems a bit scary to me. Try with promises as some user already anwered. – nada May 20 '16 at 07:39

3 Answers3

0

Have you tried with promises?

var jqxhr = $.get( url, function() {
  alert( "success" );
})
  .done(function() {
    void(0);
  })
  .fail(function() {
    void(0);
  })
  .always(function() {
    alert( "finished" );
  });
Víctor
  • 3,029
  • 3
  • 28
  • 43
0

Try this

    var loaded=false;
    $.ajax({

    url : 'your url',
    type : 'GET',
    async : false,   // You need this

    complete: function(data) {              
        loaded=true;
    },


});

 while(!loaded)  //<--locks here
 setTimeout(void(0),100);
Numan Ali
  • 223
  • 2
  • 13
0

If you work with jQuery, deferred objects are the way to go. They implement a robust and easy methodology.

However, if you want your script to work, try this:

var loaded = false;

function myfunc() {
    if (loaded) {
        clearInterval(timeout);
        doSomethingAfter();
    }
}

var timeout = setInterval(myfunc, 100);
$.get(url,function(d){loaded=true;});
Dacklf
  • 700
  • 4
  • 15