0
votes

I am trying to fix a problem with my recursive function JS using a call back. I just want to update the HTML of 3 div using according to an index. Please find the code below

<div id="try0">50</div>
<div id="try1">50</div>
<div id="try2">50</div>

function getNumberOfAnswers(questionID, callback)
{
  var value = i*10;
   callback( value.toString());

}

var i=0;
getNumberOfAnswers(i, function callFunc(ratio){
    var itemToChg = 'try'+i;
document.getElementById(itemToChg).innerHTML = ratio;
    if(i<3){
        i++;
        getNumberOfAnswers(i,callFunc(ratio));

    }

    });

I didn't put any tags on the code above to simplify but I made a JSfiddle with it. http://jsfiddle.net/cyrilGa/zmtQ8/ . On the third line from the end, I tried to write getNumberOfAnswers(i,ratio); but it didn't work. Can somebody help me with this Cheers

3
I don't know if it's possible to fix this imbricated call/declaration structure but I think you just choose the most complex way to do a simple thing. Can you explain what you exactly try to do ? - Denys Séguret
Saying "it didn't work" is useless. What did you expect? What actually happened? What errors did you get? - RobG
My actual problem is actually is bit more complex than the one above so I tried to simplify it. I am querying a parse.com database using Javascript asynchronously 10 times. So I have to wait for the end of one query (hence the callback) before querying it again. (hence the recursive part). With each result from the database, I am updating the value inside a div. Hope this is clear - Cyril Gaillard
You are right, I should have explained a bit more, I expected to have 0 in the div Try0, 10 in the Try1, and 20 in the Try3. I get 0 on all divs. So it is not incrementing the index - Cyril Gaillard
The callback calls back with the given ratio instead of referencing the function: getNumberOfAnswers(i,callFunc); - Me.Name

3 Answers

2
votes

The line:

var value = i*10; 

should be

var value = questionID * 10;

And I think

getNumberOfAnswers(i,callFunc(i));

Should be:

getNumberOfAnswers(i,callFunc);
1
votes

Do not use recursion for this, it is silly.

for ( var i = 0; i < 3; i++ ) {
    document.getElementById('try' + i).innerHTML = i * 10;
}

Is this what you want?

0
votes

You need to replace the recursive callFunc(ratio); at the bottom to callFunc(i); because the argument ratio is still equal to 0 while you increment i. Everything else is fine.