tags:

views:

50

answers:

1

I have made a loop in my JavaScript code and in that loop I use an XMLHttpRequest with a callback method but I'm having a problem with it.

When my loop ends the callback executes. This is not good, I need the callback to execute after calling a function, not after looping. How can I do this?

Somebody on a blog wrote that I can use an async method. How can I use an async method in this condition?

for (var i = 0; i < stuff.length; i++) {
                        var exist = IsstuffExist(stuff[i]);
                        alert(exist);
                    }

the called function show alert();

when i call function then i got alert of my code first and callback alert comes after my code.

how i can stop loop for sometime then i can get back response as callback from called function

if i use in looping

 IsstuffExist(tags[i], function (result) {
                            if (result == true) {
                                $("#txtstuff").append(stuff[i]);
                            }
+5  A: 

You basically have to change your thinking. You need to change your style from writing code like this:

for (var i = 0; i < stuff.length; i++) {
    var exist = IsstuffExist(stuff[i]);
    alert(exist);
}

to writing stuff like this:

for (var i = 0; i < stuff.length; i++) {
    IsstuffExist(stuff[i], function(exist) {
        alert(exist);
    });
}

the IsstuffExist function can be written like this:

function IsstuffExist (stuff, callback) {
    // Do things and once you get the `exist` variable you can
    // pass it to the callback function. Any code that needs
    // to continue processing things can then resume from
    // within the callback function:
    callback(exist);
}

This technique can be nested, passing the callback function to other callback functions. A concrete example is with ajax calls:

// I'm using my own ajax library in this example but it's the same
// if you use other libraries:

function IsstuffExist (stuff, mycallback) {
    // Make ajax call to find out if stuff exist:
    ajax('some/url.com', {
        callback : function (r) {
            var status = r.responseText;
            mycallback(status);
        }
    });
}

note: I renamed the callback for the function to mycallback to avoid confusion. But in real code I would simply name it callback.

So now instead of writing code like this:

for (var i = 0; i < stuff.length; i++) {
    if(IsstuffExist(stuff[i])) {
        doSomethingAndUpdateTheHTML();
    }
}

you write it like this:

for (var i = 0; i < stuff.length; i++) {
    IsstuffExist(stuff[i],function(exist){
        if (exist) {
            doSomethingAndUpdateTheHTML();
        }
    });
}
slebetman
+1 for comprehensive answer!
JBRWilkinson