Joel Enanod Jr
Joel Enanod Jr

Reputation: 669

javascript/jquery loop execute function after every iteration

var dagaData = ['Manok', 'Pusa', 'Daga', 'Ibon', 'Aso'];
$('#clicktest').on('click', function() {
    $.each(dagaData, function(index, item) {
        executeData(item);

        alert(item);
    });
});

function executeData(item) {
    var items = $("<div></div>").text(item);
    $('#pangtest').append(items);
}

Is it possible to execute the function on every iteration?

Right now when I run the code above it finished all iteration before the append happen.

That why I've put alert to see if every alert append each iteration.

Output of code above: alert('Manok'), alert('Pusa') ,alert('Daga'), alert('Ibon'), alert('Aso') executed append.

What I'm trying to achieve is alert('manok') append, alert('Pusa') append, alert('Daga') append, alert('Ibon') append, alert('Aso') append.

Thanks in advance.

Upvotes: 0

Views: 94

Answers (2)

nnnnnn
nnnnnn

Reputation: 150030

In a general sense, although the DOM is updated each time you call .append() the browser won't actually repaint the screen until after the entire JS function finishes. (Though some browsers will repaint at the point when an alert is open, which is why using alert() for debugging is a bad idea: it can subtly change the behaviour in a way that calling console.log() doesn't.)

You can work around this by using a setTimeout-based pseudo-loop - in between timeouts the browser then gets a chance to repaint:

var dagaData = ['Manok', 'Pusa', 'Daga', 'Ibon', 'Aso'];

$('#clicktest').on('click', function() {
  var i = 0;  
  (function doNext() {
    var item = dagaData[i];
    executeData(item);
    alert(item);
    if (++i < dagaData.length)
      setTimeout(doNext, 5);
  })();
});

function executeData(item) {
    var items = $("<div></div>").text(item);
    $('#pangtest').append(items);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="clicktest">Test</button>
<div id="pangtest"></div>

Or just use your original $.each() loop with the contents of the loop wrapped in a timeout, as per Bnrdo's answer. But I prefer to wait to schedule each timeout only after the previous one is done because that way the order of execution is guaranteed.

Upvotes: 2

Bnrdo
Bnrdo

Reputation: 5474

Wrap them in setTimeout

$.each(dagaData, function(index, item) {
   setTimeout(function() {
      executeData(item);

      alert(item);
   }, 1);
});

Upvotes: 2

Related Questions