Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

javascript - Wait for callback before continue for loop

I've a for-loop I'm looping through.

I want to make a custom modal and wait for a response before continue it.

How can I achieve this? I know I've to wait for a callback.

Like this example:

 for(var x in array){
            alert(x);
            console.log(x);
        }

It does exactly what I want to. But I want to have three buttons. But alert is not part of javascript(? It's in the browser.)

So, do you guys have an idea?

I was thinking about doing something like this:

var run = true;
function foo(){
    if (run){
        setTimeout(foo, 500);
    }
}

function stop(){
    run = false;
}

foo();

and then wait for a stop which calls on a button click before continue. But is this really good practice?

Or use a lambda function as a parameter to the customAlert and a "global" variable that holds the current position of the array I'm going through and do this with functions. Like: Check if array is still holding keys greater than X. Then do the function again and each time increase the global X.

Thank you lostsource for the code: Oh, I got an idea; I'll simply use lostsource's solution inside an anonymous function, so I don't get global variables. Excellent.

(function(){

})();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming this is your array

var list = ['one','two','three'];

You can try using this loop / callback approach

var x = 0;
var loopArray = function(arr) {
    customAlert(arr[x],function(){
        // set x to next item
        x++;

        // any more items in array? continue loop
        if(x < arr.length) {
            loopArray(arr);   
        }
    }); 
}

function customAlert(msg,callback) {
    // code to show your custom alert
    // in this case its just a console log
    console.log(msg);

    // do callback when ready
    callback();
}

Usage:

// start 'loop'
loopArray(list);

JSFiddle here: http://jsfiddle.net/D9AXp/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...