How can I call ajax synchronously without my webpage freezing

I have javascript that misses about 100 calls to a php script. The PHP script uses most of the memory and takes a few seconds, and then returns a json pass or fail response.

I don’t want the ajax calls to be asynchronous, since the server would stop interrupting using 100 instances of itself, so I tried using synchronous, the only problem is freezing the web page when it calls the script one call at a time .

How can I disable ajax calls one at a time and not freeze the page I'm on?

var a = [];
    a[0] = 'test';
    a[1] = 'hello';
    a[2] = 'another';

$(document).ready(function(){ 
  $.each(a, function(k,v) {
$.ajax({
  url:'/this-script-takes-a-few-seconds-to-complete.php',
  async:false,
  data: {foo: v},
  success: function(data){      
    console.log(data);  
  }
});
  });
});
+3
source share
6 answers

, , success, :

$(function(){ 
  var i = 0;
  function nextCall() {
    if(i == a.length) return; //last call was last item in the array
    $.ajax({
      url:'/this-script-takes-a-few-seconds-to-complete.php',
      data: { foo: a[i++] },
      success: function(data){      
        console.log(data);  
        nextCall();
      }
    });
  }
  nextCall();
});

... , 100 , - , .

+14

, , , . ? , 100 , , , .

+3

. 100 ajax , .

, , 100.

100, - .

+1

, , Ajax... " JavaScript XML"...

Ajax Ajax .

async.

0

-

HTTP- , -, , , ( ). , , , , "2", Firefox 2005 .

:

script $.ajax 2 , a. - , , . , , .

, script - a , . a, .

a = [
    'test',
    'hello',
    'another'
];

$(function() {
    var send = function() {
        $.ajax({
            url: '/this-script-takes-a-few-seconds-to-complete.php',
            async: false,
            data: {foo: a.shift()},
            success: function(data) {
                console.log(data)
            }
        });

        if (!a.length)
        {
            clearInterval(timer);
        }
    }

    var timer = setInterval(send, 2000);
});
0

, , IE . .

  • synchroniou async: true.
  • Recall the following ajax request in the complete function :.

This allowed me to call a synchronous call asynchronously, so I called after a previous call.

-1
source

Source: https://habr.com/ru/post/1773073/


All Articles