Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
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){

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;


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.


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) {
        // set x to next item

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

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

    // do callback when ready


// start 'loop'

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

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share