Hello there, am a javascript newbie and am puzzled by something I’ve never seen in c++ (am used to this).
I have a loop in a function like this:
javascript code:
function fn()
{
var found = false;
for(var index = 0; index <= 20; index++)
{
another_fn(index,found); //use index
if(found == true) //editted here, found should be changed within another_fn
break;
}
}
this loop executes 20 times first and then my function is called with the same value of index 20 times, is there a way I could make sure that the function another_fn is called once per an increment of index;
It won’t call with the same value for index 20 times, but right now found will never change. it is already being called once for every iteration over index.
Scoping. found is passed to another_fn by value, not by reference. I’m rusty on my C++, but I believe that it passes arguments by value as well, which is why you have to use a pointer in order to pass in a shared resource.
Thank you very very much for your help, i understand stuff about references well i’ll check out how to pass references in JS in a moment but for now, there is another bigger problem i wish you help me understand, You see in c++ if i run that code “my first post” the function will be called for every single increment of variable index but in JS for some reason the loop runs to completion first then my function gets called 20 times later, Do you know of anyway i can force this loop to behave similar to the behavior i described in c++.
am using chrome to test a js file am editing, and it’s just mind boggling.
let me show you my real code, you see i have this confused code i just don’t get it, seriously that is what is happening, i have never seen something like it ever.
Do you see the code: i’ve commented out the important lines in assetOpen but i just can’t get how the alert() happens 20 times then navigateToPageNum gets called 20 times later, it’s really weird @####
the only thing i need help with is just removing that logical error, where the alert() is called 20 times then my function gets 20 calls later. please anyone?
I think that the nature of alert might be making the timing confusing. Here I have replaced both the call to alert and the body of the function with console logs, so you can see that they are called in sequence. (I had to comment out a bunch of unrelated code to run it).