[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

0 Response to "[JS] How to delay ajax one by one in loop"

Post a comment

Bila Ada posting yang kurang, atau error atau yang lainnya, silahkan tinggalkan komentar agar artikel/post di perbaiki.
Jangan Lupa Cek Box "Notify Me" agar tahu komentar kamu dibalas oleh saya.

If there are any posts that are missing, or error or anything else, please leave a comment for the article / post to be fixed.
Do not Forget Check Box "Notify Me" to know our comments replied by me.

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel

loading...