$(function() {
$("#submit").click(function() {
for (var i=1; i<=14; i++)
{
setID(i);
checkField(i);
}
if ($('#pass_fail').val() != "fail")
{
//do something
}
This is what happens when I click on the submit button of a registration form.
Order of execution I want:
setID(1);
checkField(1); //wait for this to finish
setID(2);
checkField(2);
setId(3);
checkField(3);
....
if statement
Order of execution I get:
for loop going from i=1 to i=14
if statement
checkField(i)s in random order
Problem: $('#pass_fail').val() has a default value of 'pass'. However through the loop checkField(i) might change its value to 'fail'. But since in reality the if statement is executed before checkField(i)s, the value of $('#pass_fail') always ends up being 'pass' and the 'do something' always executes.
How do I wait for checkField(i) to finish executing before moving on to the next iteration of the looP? Thank you in advance!
I'm assuming from your description of the issue that
checkField()
is making some sort of asynchronous Ajax call. If you truly want to serialize the calls tocheckField()
so the 2nd call is not made until the first has completed, then you need to change the structure and flow of your code in order to do that. The two common ways of doing so are either using a callback that indicates completion of a call tocheckField()
that triggers the next call tocheckField()
or the use of promises to accomplish something similar.Here's an example of the callback mechanism:
Then,
checkField()
would have to be modified to call the callback passed to it when it completes its asynchronous operation.If you're using jQuery to make the ajax operations inside of checkField, it would be fairly easy to use jQuery promises to solve this also.
Sorry, but in earlier response I didn't see any loop to wait for any other function or any inner loop execution to let it finish before next iteration.
With
JQuery 3.3.1
Scenario:
for loop
withvar i
will wait for inner other loop to complete before next iteration value ofi
Hope this would help many one.