简体   繁体   English

在循环中使用回调的正确方法?

[英]RIght way to use callback in with loops?

I have been trying to learn callback functions and I've spent a few days but I'm not able find a working example of using callback in nested loops. 我一直在尝试学习回调函数,花了几天时间,但找不到在嵌套循环中使用回调的有效示例。 I have provided a sample code here in the fiddle where data should be pushed for each of the value.But all it is returning an empty array. 我在小提琴中提供了一个示例代码,其中应该为每个值推送数据,但所有操作都返回一个空数组。

I want data to have i value , j times in it while the loop doesn't work in synch.So an empty array is being returned 我希望数据具有i值,其中j次,而循环无法同步进行,因此返回了一个空数组

I'll be using the concept in project where timeout will be replaced by sqlite insertion and select.This is an example just to know how to use it within loops. 我将在项目中使用这个概念,其中超时将被sqlite插入并选择替换。这是一个示例,旨在了解如何在循环中使用它。

var data = [];
for(var i = 0;i<100;i++) {
loop(i);
}
function loop(i) {
for(var j =0;j<200;j++) {
    p(i);
}
}

function p(val) {
setTimeout(function(){
    data.push(val);
},10)

}
console.log(data);

Here is the example of a working fiddle. 这是一个有用的小提琴的例子。

This question is similar to mine but I'm not able understand how to use it in my case. 这个问题类似于我的问题,但是我无法理解如何使用它。

I just want to get array having (iXj) values in data variable Thanks in advance. 我只想获取在数据变量中具有(iXj)值的数组,谢谢。

 var i = 0; var length = 10; function for1() { console.log(i); for2(); } function for2() { if (i == length) { return false; } setTimeout(function() { i++; for1(); }, 500); } for1(); 

Here is a sample code I developed as I had to spend a lot of time to understand what call back is as the term was confusing to me.Then I tried to use this approach hope it helps. 这是我开发的示例代码,因为我不得不花很多时间来理解术语使我感到困惑的回叫。然后我尝试使用这种方法希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM