0

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.

Kobey24
  • 117
  • 1
  • 1
  • 9
  • How are you using it in non-nested loops? Please tell us what you know about those. – Bergi Jun 15 '17 at 17:51
  • If your fiddle is working, what's the problem? – Bergi Jun 15 '17 at 17:51
  • My fiddle is working but it is returning an empty array while it should be array of all the values of i , j times – Kobey24 Jun 15 '17 at 17:52
  • So it's *not working* as expected?! – Bergi Jun 15 '17 at 17:54
  • 1
    Yes that's why I have asked for using callback because I don't have a command over them to use them my way.One thing more 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. – Kobey24 Jun 15 '17 at 17:58
  • What would be your way to use them? – Bergi Jun 15 '17 at 17:59
  • I don't have a way.I have seen simple examples of callback showing functions used in synchronous way but I'm not sure how to use them with loops – Kobey24 Jun 15 '17 at 18:00
  • 1
    Possible duplicate of [Asynchronous Process inside a javascript for loop](https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) – Frxstrem Jun 15 '17 at 18:02
  • By "synchronous" I guess you mean "sequential". Are you expecting your timeouts to occur after each other, or concurrently? – Bergi Jun 15 '17 at 18:02
  • Yes you are right a more of a sequential way.Because in my project I'm not sure about how much time my sqlite query will take – Kobey24 Jun 15 '17 at 18:04

1 Answers1

1

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.

Black Mamba
  • 11,092
  • 6
  • 67
  • 93