ramcrys ramcrys - 1 year ago 111
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):


$('#searchBtn').click(function () {
type: 'GET',
url: 'searchRepo',
async: true,
beforeSend: function () {
complete: function() {
success: function (result) {


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

Answer Source

First off, change your server code to:

router.get('/searchRepo', function (req, res) {
   setTimeout(function() {
   }, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download