0 votes
in Programming by (2k points)

I have the following javascript. What I want it to do is wait until a getJSON has returned, in which a flag is set, and then do something. However after finding the check function below on SO, I can't actually get it to log loaded even when flag is true (and so processData is never executed). What am I doing wrong?

flag = false
        $.getJSON(<url>,
            function(params){ 
                if (params){
                    flag = true;
                 }
            }
        );
 var check = function() {
        console.log("check A");

        if (flag === false) {
            console.log('still going to check');
            return setTimeout(200, check);
        }
        console.log("loaded!");
        processData();
    }
    check();

can anyone help me?

1 Answer

0 votes
by (2.4k points)

You need setTimeout(check, 200); rather than setTimeout(200, check);. You'll also have to explicitly set flag to false before running the function.

However, you could just go with:

    $.getJSON(<url>,
        function(params){ 
            if (params){
                check();
             }
        }
    );
    var check = function() {
       console.log("check A");
       console.log("loaded!");
       processData();
    }

 

131 questions

117 answers

7 comments

378 users

Welcome to Todayask Q&A, where you can ask questions and receive answers from other members of the community.
...