在继续循环之前等待回调 [英] Wait for callback before continue for loop

查看:104
本文介绍了在继续循环之前等待回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环我正在循环。

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.

就像这个例子:

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

它完全符合我的要求。但我想要三个按钮。
但警报不是javascript的一部分(?它在浏览器中。)

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?

我在考虑这样做:

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?

或者使用lambda函数作为customAlert的参数和一个全局变量来保存数组的当前位置我是通过功能完成并执行此操作。喜欢:检查数组是否仍然保持大于X的键。
然后再次执行该函数,每次都增加全局X.

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.

谢谢你的遗失资源代码:
哦,我有个主意;我只是在匿名函数中使用lostsource的解决方案,所以我不会得到全局变量。非常好。

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(){

})();


推荐答案

假设这是你的数组

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();
}

用法:

// start 'loop'
loopArray(list);

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

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

这篇关于在继续循环之前等待回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆