简体   繁体   中英

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'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.

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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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