最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript: wait for function in loop to finish executing before next iteration - Stack Overflow

programmeradmin5浏览0评论
$(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!

$(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!

Share Improve this question asked Jun 10, 2014 at 1:26 user2973438user2973438 3112 gold badges6 silver badges9 bronze badges 3
  • 1 to convert async functions into synchronous ones, you might need to refactor checkField to take a callback of the next checkField. – Fabricator Commented Jun 10, 2014 at 1:32
  • 1 So, checkField() performs a server request? Why not grab all fields together and check them all at once? – Ja͢ck Commented Jun 10, 2014 at 1:34
  • right, checkField() contains an Ajax call which accesses a php file with functions checking different fields. The reason why I can't perform a single call for all the fields is because each call returns a different error msg, corresponding to THAT field. If a single checkField() checks all fields at once, then errors for all different fields will be displayed under the same field. – user2973438 Commented Jun 10, 2014 at 1:52
Add a ment  | 

2 Answers 2

Reset to default 3

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 to checkField() so the 2nd call is not made until the first has pleted, then you need to change the structure and flow of your code in order to do that. The two mon ways of doing so are either using a callback that indicates pletion of a call to checkField() that triggers the next call to checkField() or the use of promises to acplish something similar.

Here's an example of the callback mechanism:

$("#submit").click(function() {
    var i = 0;
    function next() {
        i++;
        if (i <= 14) {
            setID(i);
            checkField(i, next);
        } else {
            // all checkField operations are done now
            if ($('#pass_fail').val() != "fail") { 
                //do something
            }
        }
    }
    next();
});

Then, checkField() would have to be modified to call the callback passed to it when it pletes 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 with var i will wait for inner other loop to plete before next iteration value of i

$(document).ready(function(){

    $("p").click(function() {
    
    	var varIDeferred = $.Deferred();
        var varJDeferred = $.Deferred();
        
        /*
        var loopJInside = function(j) {  
            console.log("j is : " + j);
            $("span").html($("span").html() + "<br>j is : " + j);
            varJDeferred.resolve();
            j++;
            console.log("j value after incr is : " + j);
            return j;
        }
        
        // call inside loopJ
        setTimeOut(j = loopJInside(j), 500);
        */
        
        var loopJ = function(valueI) {
        
            for (var j = valueI; j < (3+valueI); ) {
        	    
        	varJDeferred = $.Deferred();
                $("span").html($("span").html() + "<br>j is : " + j);
                j++;
                varJDeferred.resolve();
                
            }
            
            varIDeferred.resolve();
            
            return (valueI+1);
        };
        
       	for(var i = 0; i < 3; ) {
       	    
       	    varIDeferred = $.Deferred();
       	    
	    $("span").html($("span").html() + "<br>value of i is : " + i);
            
            if (i == 3)
                break;
            	
            i = loopJ(i);
        };
        
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<p style="cursor:default;border:2px solid black;width:60px;padding:5px;">Click me</p>
<span><span>

</body>
</html>

Hope this would help many one.

发布评论

评论列表(0)

  1. 暂无评论