0

I have the following code:

$('#DoButton').click(function (event) { event.preventDefault(); $("input:checked").each(function () { var id = $(this).attr("id"); $("#rdy_msg").text("Starting" + id); doAction(id); }); }); function doAction(id) { var parms = { Id: id }; $.ajax({ type: "POST", traditional: true, url: '/adminTask/doAction', async: false, data: parms, dataType: "json", success: function (data) { $("#rdy_msg").text("Completed: " + id); }, error: function () { var cdefg = data; } }); } 

When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. The delay is to give the user time to see that the last action has completed.

By setting async=false will that really make the ajax function wait?

How can I add a 2 second wait after the Ajax has run and before the next call to doAction?

2
  • 1
    Could you clarify, you want to wait so the user can know that the action was completed. If you make your code synchronous, that means nothing in the webpage will work until after it has been run (think about how a program freezes while it is doing something). I would recommend maybe displaying a message after, or graying out the button instead. subtle cues are the best cues. Commented Jun 26, 2011 at 5:38
  • 1
    possible duplicate of How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request? Commented Jun 26, 2011 at 5:54

3 Answers 3

2

There is option in jQuery to set the ajax function synchronous

$.ajaxSetup({ async: false }); 

To make the function to wait you can use .delay()

Try the solution of this question also.

Sign up to request clarification or add additional context in comments.

Comments

1

Try to do it using recursion

$('#DoButton').click(function (event) { event.preventDefault(); doAction( $("input:checked").toArray().reverse() ); }); function doAction(arr) { if( arr.length == 0 ) return; var id = arr.pop().id; $("#rdy_msg").text("Starting" + id); $.ajax({ type: "POST", traditional: true, url: '/adminTask/doAction', async: false, data: { Id: id }, dataType: "json", success: function (data) { $("#rdy_msg").text("Completed: " + id); setTimeout(function(){ doAction(arr); }, 2000); }, error: function () { var cdefg = data; $("#rdy_msg").text("Error: " + id); setTimeout(function(){ doAction(arr); }, 2000); } }); } 

Comments

-1

Use setTimeout for the AJAX call doAction.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.