ramcrys ramcrys - 1 month ago 8
Ajax Question

Ajax call to Express server freezes the UI

I have a simple app where clicking on the button makes an Ajax call (asynchronously) to an Express server.

In the Express route handler, I simulate a long running operation by doing a loop (this is just a demo, in the future I intend to do a remote request to a Java REST API here).

The result is that the UI freezes here (the loading image does not even show during the time). Could you help me to spot the problem here ?
Following is the code (I have tried with both POST and GET methods, still the same issue):

Client

$('#searchBtn').click(function () {
$.ajax({
type: 'GET',
url: 'searchRepo',
async: true,
beforeSend: function () {
$('#testDiv').html('');
$('#loadingIc').show();
},
complete: function() {
$('#loadingIc').hide();
},
success: function (result) {
$('#testDiv').html('<div>Test</div>');
}
});
});


Server

router.get('/searchRepo', function (req, res) {
sleep(10000);
res.send('aaaaa');
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}

Answer

First off, change your server code to:

router.get('/searchRepo', function (req, res) {
   setTimeout(function() {
       res.send('aaaaa');
   }, 10000);
});

As this more accurately simulates a long running remote request.

Second off, add an error handler to your ajax code so in case you're getting a timeout or some error, you will know that is happening.

Your version of sleep() was killing your single threaded node.js server so it could do nothing else for 10 seconds. If your web page happened to be waiting on other resources to be served by the node.js server (style sheets, script files, etc...), it would get hung up waiting for your server to get unbusy.

I don't see anything else disclosed in your code that would "freeze" the browser. You are using async: true which is required to keep from freezing the browser. If #loadingIc is something visible, it should be visible during your ajax call. You'd have to show more of the browser context for us to have an idea what else might be going on there.

Also, when you say "freeze" what exactly do you mean? Are you seeing high CPU usage and complete non-responsiveness of any browser UI? Or are you just not seeing the #loadingIc UI? If it's the former, then your ajax call is probably not properly async. If it's the latter, then there is probably a display problem with the #loadingIc UI.

Comments