0

I'm new to jQuery, and I have been playing around with it a bit. I have one UI element called result, which is updated once the result arrives and this works perfectly. However, this result comes from a series of computations.
Now I want the UI element to update after each computation to show some sort of progress. However, if I set the value of the UI element inside this recursive function I'm using for computation, it doesn't update it. Here's the code:

function getRes(val) {
  if(val === finalVal)
    return;
  // do something 
  $("#result").text(someVal); //This doesn't work
  getRes(val+1);
}

$("#resbtn").on('click', function(){
  getRes(0);
  $("#result").text(res);  //This works
});

Why is this happening?

Zeokav
  • 1,543
  • 4
  • 13
  • 29

2 Answers2

0

You need to trick the browser into refreshing the DOM. See Why is setTimeout(fn, 0) sometimes useful?

function getRes(val) {
    if(val === finalVal)
    return;
    // do something

    setTimeout(function() {
        $("#result").text(someVal); //This doesn't work
        getRes(val+1);
    }, 0);
}

$("#resbtn").on('click', function(){
    getRes(0);
    $("#result").text(res);  //This works
});
Community
  • 1
  • 1
plarner7
  • 150
  • 6
0

Your code works fine. I logged into another div each pass into your recursive function :

var finalVal = 100;
var someVal;

function resetLogs() {
  $("#log").html('<h3>Logs</h3>');
}

function getRes(val) {
  if(val === finalVal)
    return;
  // do something 
  someVal = "Loading : "+val+'%';
  $("#log").append(someVal+'<br>');
  $("#result").text(someVal);
  getRes(val+1);
}

$("#resbtn").on('click', function(){
  resetLogs()
  getRes(0);
  $("#result").text("FINAL");
});

$("#resbtn2").on('click', function(){
  resetLogs()
  getRes(0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">initial content</div>
<button id="resbtn">With 'final'</button> <button id="resbtn2">Without final!</button>

<div id="log">
  <h3>Logs</h3>
</div>

The problem may be that you go trough your recursive function so fast that the displayed data haven't enough time to be properly displayed and is quickly replaced by the final value to display (here "FINAL" string)

Sir McPotato
  • 839
  • 7
  • 21