A.Mokhtari
A.Mokhtari

Reputation: 461

How to Handle delays that made by multiple timeouts (containing ajax calls)

Consider I have multiple (sometimes more than 12) ajax calls that are calling every 2 seconds or more. Data gathered through the calls are set to the UI contained elements (Like progress bars). After all I have delay on SCROLL while timers working . This delay is natural, But How can I handle it?

NOTE: Calls Destinations are services that provides data with the minimum spent time. The point that makes the scroll sad, is using multiple setTimeout() and setInterval() methods. To get more familiar with my work, See the below code:

function FillData(accessUrl, name) {
            var add = accessUrl;
            $.support.cors = true;
            if (add) {
                $.ajax({
                    type: 'GET',
                    url: accessUrl,
                    crossDomain: true,
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (data) {
                        Update(name, data);
                    },
                    error: function (xhr, status, error) {
                        LogResponseErrors(status , error, name);
                    }
                });
                setTimeout(function () { FillData(accessUrl, name); }, interval);
                //Consider that the method calls with different parameters one time and it will run automatically with setTimeout
            }
            else {
                freezeFrame(name);
            }
    }

Used Tags explains what I used.

Any useful answer will be appreciated

Upvotes: 0

Views: 188

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

From what I understand in your question. You have delay when you're handling your ajax responses and you need to remove the delay.

Javascript is single-threaded. Therefore, if there is a function that takes long time to complete, it could dominate the thread and cause the UI not responding. To deal with this, you have 2 options:

  • Optimize your code so that the function does not take long.
  • Use setTimeout to break your function into smaller pieces. For example: if your function is executing a loop of 100 items, you could break it to execute 10 times with 10 items each.

Update: (based on updated question):

It seems that the loop never stops when you use setTimeout like this. Should have something like:

counter++;
if (counter <= 12)
setTimeout(function () { FillData(accessUrl, name); }, interval);

Due to timing problem between ajax and your setTimeout, at some points, there are a lot of events (escalated) waiting in the queue to be executed and cause performance problem. Try putting your setTimeout inside your success or complete function

Upvotes: 1

Related Questions