[JS] How to delay ajax one by one in loop

Bahasa indonesia: Bagaimana eksekusi ajax satu per satu di Loop
<div id="demo"></div>
<script>
/**
 * Define global variable
 * @var {int} indexLoop global loop indexer
 * @var {int} lastLoop global last iteration for global loop indexer from loop initializer
 * @var {array} queueLoop global array to be processed from ajax
 * @var {array} arrayLoop define array to be proccesed
 */

var indexLoop = 0,
  lastLoop = 0,
  queueLoop = [],
  arrayLoop = ['apple', 'melon', 'watermelon', 'grapes'];

for (var i = 0; i < arrayLoop.length; i++) {
  queueLoop.push(arrayLoop[i]);
  if (i == arrayLoop.length - 1) {
    lastLoop = i + 1;
    ajaxLoop(function () {
      var b = document.createElement('b');
      b.innerHTML = 'Processing all item ' + indexLoop + ' of ' + lastLoop + ' succedeed<br/>';
      document.getElementById('demo').appendChild(b);
    });
  }
}
/**
 * Initialize global ajaxLoop function
 * @param {function} lastFunction function to be executed on last iteration
 */
function ajaxLoop(lastFunction) {
  if (indexLoop < lastLoop) {
    $.ajax({
      url: 'https://reqres.in/api/users?page=' + (indexLoop + 1),
      beforeSend: function () {
        var b = document.createElement('b');
        b.innerHTML = 'Processing item ' + indexLoop + ' of ' + lastLoop + '<br/>';
        document.getElementById('demo').appendChild(b);
      },
      success: function (response) {
        var b = document.createElement('b');
        b.innerHTML = 'Processed item success ' + this.url.split('=')[1] + ' of ' + lastLoop + '<br/>';
        document.getElementById('demo').appendChild(b);
      },
      error: function () {
        var b = document.createElement('b');
        b.innerHTML = 'Processed item error ' + this.url.split('=')[1] + ' of ' + lastLoop + '<br/>';
        document.getElementById('demo').appendChild(b);
      },
      complete: function () {
        var b = document.createElement('b');
        b.innerHTML = 'Processed item complete ' + this.url.split('=')[1] + ' of ' + lastLoop + '<br/>';
        document.getElementById('demo').appendChild(b);
      }
    });

    indexLoop++;
    ajaxLoop();
    if (indexLoop == queueLoop.length) {
      if (typeof lastFunction == 'function') {
        lastFunction();
        /** reseting global indexer */
        indexLoop = 0;
      }
    }
  }
}
</script>

preview

Delay ajax in loop

Comments

Popular posts from this blog

Install deb package via Termux

How to Make Blogger Safelink Converter v3

List of weapon buff materials, effects and how it can be durango wild lands