0

What I need is for javascript to keep checking for a condition (similar to a while loop). I am doing this by doing a setInterval and if the condition is met, I clear the interval which then exits or if it has run X amount of times, in the case I have below I have it set to 100.

I don't like this that much, I threw it together because it works. I am checking data from a server and this is sluggish. My main reason why I want an alternative is that I have a loading gif that runs when an AJAX call is started, I'll paste this code at the bottom just to show. It is running sluggish so I believe while the javascript is in the interval, it isn't able to render the gif so the moving image just stops.

Anyone know of an alternative to do what I want? I hope this makes sense?

function checkCondition(name,action){
    var timesRun = 0;
    var success = false;

        var interval = setInterval(function() {
            timesRun++;
            var container = {};
            container = mapSystem["desktop"];

            if(action === "delete"){
                var isExisting = name in container ;
                if ( !isExisting || (timesRun === 100)) {
                    //break out of this interval
                    clearInterval(interval);
                    renderCheckList();
                    success = true;
                } else {
                    // Update mapNodeData with fresh data
                    updateData('desktop', false); // Just updates data
                }
            }
        }, 2000);
}

// Code that I have to render a loading GIF. Works great but seems 
// to stop during the interval
$('#loading').hide().ajaxStart(function() {
                $(this).show();
             }).ajaxStop(function() {
                $(this).hide();
            });
Envin
  • 1,463
  • 8
  • 32
  • 69
  • 3
    AJAX has a SUCCESS callback, you should be able to determine when the service is finished by hooking up your code in there, not by polling for it. The A in AJAX = asynchronous. – Diodeus - James MacFarlane Mar 04 '13 at 21:05
  • Watch this link. This may be interesting for you (If I understand you right) .. http://stackoverflow.com/a/1269692/171318 – hek2mgl Mar 04 '13 at 21:06
  • 1
    For clarity, in the updateData call, I am running an ajax call to retrieve updated data from the server. – Envin Mar 04 '13 at 21:07
  • @Diodeus I have a few things already in the success callback that works great. This function is actually called in the success function of the main action (for the example when I delete a computer node in a javascript tree I have, this checks to ensure it is deleted before refreshing). The API call I am making to the backend needs to process so it may not be done by the time the javascript call finishes which is why I want to check manually. – Envin Mar 04 '13 at 21:09
  • The JavaScript "call" should not "finish" until the server sends a response. The server response generally indicates the process has completed. – Diodeus - James MacFarlane Mar 04 '13 at 21:12
  • 1
    Right, I receive a response but it is just a job response. The cloudstack software is processing the action in the background. It doesn't take long by any means but sometimes I noticed the javascript would be executing before it happened. For example, if I delete something, sometimes it needs to "stop" and then delete, so multiple things are happening. I'm trying to not explain too much of the backend since it isn't too important here (at least I don't think). – Envin Mar 04 '13 at 21:14
  • How much processing are you doing in `updateData`? Is there any way to cut-down/optimize this code? I think that would help with your loading.gif problems. – Ben Mar 04 '13 at 21:17
  • Not too much since I am narrowing it down by what I need. It is only one AJAX call in the above example. I used to load EVERYTHING before which is about 30 ajax calls, but I implemented caching and created `updateData` to update mapSystem with only what I need. – Envin Mar 04 '13 at 21:19
  • My other question is: Is the original ajax call returning anything useful? If not, maybe you should delay completing that request until all the updates on the server-side have completed. That would eliminate the need for the polling code. – Ben Mar 04 '13 at 21:31
  • It is returning JSON which I am using to render different levels of the jsTree I am creating. The user is selecting an action on the tree, which has already been rendered and the action takes place through an AJAX call and then I update the data by getting the data back to refresh the tree. – Envin Mar 05 '13 at 12:47

1 Answers1

1

If you use .ajax() instead of ajaxStart, you can set a function to execute when the action has completed:

From the docs:

complete

Type: Function( jqXHR jqXHR, String textStatus )

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

You also can specify a different function for success or failure using the success and error attributes.

Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
  • 1
    The loading image is seperate from the main code. I have the loading image ajaxStart/ajaxStop located in my html page. I have the other code in my javascript file for that html page, I figured it would be easier to set global ajaxStart and stop to do the loading instead of adding it to every ajax call -- there are quite a few depending on what the user chooses. My main issue is finding an alternative to setInterval. – Envin Mar 04 '13 at 21:12
  • well use callbacks on your other calls to the server then. You shouldn't have to repeatedly check to see when things have changed. You can just check when the call returns and act based on the state then. You're not showing us your relevant server calls apparently, so its tough to say more than that. – Ben McCormick Mar 04 '13 at 21:22