1

I use the code below to wait, then do next loop:

function loop()
{
    setTimeout(function()
    {
        process_number(a[i]);
        i++;
        if (i < a.length)
            loop();
        else
        {
            alert("done!");
        }
    }, 5000);
}

I want to change to like jQuery $.get callback function executed when get complete .

$.get("test.cgi", { name: "John", time: "2pm" },
  function(data){
  alert("Data Loaded: " + data);
});

function loop()
{
    //where process_number executed complete, do next loop
    //process_number(a[i]);
    i++;
    if (i < a.length)
        loop();
    else
    {
        alert("done!");
    }
}

the function process_number Execution time is uncertain.

3
  • what happens at process_number(a[i]);? (and if it is irrelevant, you shouldn't have included it) and what is the first value of i? Commented Apr 17, 2012 at 15:54
  • process_number(a[i]) is the process data function, it is very Important. i first value is 0. @ajax333221 Commented Apr 17, 2012 at 16:04
  • I meant like irrelevant to the question, (i know it is important to you). In this site you are supposed to shrink down your code to the less code possible to reproduce the problem. But well, not everyone spend 1 hour reading faq before posting Commented Apr 17, 2012 at 16:10

2 Answers 2

1

You can add a callback parameter to your loop() function and execute it when desired:

function loop(callback)
{
    //where process_number executed complete, do next loop
    //process_number(a[i]);

    if (callback) {
        callback();
    }
}

loop(function () {
    alert("continuing...");
});
Sign up to request clarification or add additional context in comments.

Comments

1

Very basically you can just pass a function name as a parameter and then call it though the argument name, this works just as well with anonymous functions:

function foo(x,callback)
{
    callback(x);
}

foo("hello",alert)
foo("hello",function(x){alert(x);});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.