gpt4 book ai didi

javascript - 在继续 for 循环之前等待回调

转载 作者:IT王子 更新时间:2023-10-29 03:18:02 26 4
gpt4 key购买 nike

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

我想制作一个自定义模式并在继续之前等待响应。

我怎样才能做到这一点?我知道我必须等待回电。

像这个例子:

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

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

那么,你们有什么想法吗?

我正在考虑做这样的事情:

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

function stop(){
run = false;
}

foo();

然后等待在继续之前调用按钮单击的停止。但这真的是好做法吗?

或者使用 lambda 函数作为 customAlert 的参数和一个“全局”变量,该变量保存我正在经历的数组的当前位置,并使用函数执行此操作。比如:检查数组是否仍然持有大于 X 的键。然后再次执行该函数,每次都增加全局 X。

感谢 lostsource 提供的代码:哦,我有个主意;我将简单地在匿名函数中使用 lostsource 的解决方案,因此我不会获得全局变量。太棒了。

(function(){

})();

最佳答案

假设这是你的数组

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

您可以尝试使用这种循环/回调方法

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 在这里:http://jsfiddle.net/D9AXp/

关于javascript - 在继续 for 循环之前等待回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com