progNewbie
progNewbie

Reputation: 4832

Polling: Do Get-Request until result suits

I have the following code:

$.get( "GetJobResult", { jobId: jobId }, function( answer ) {

})

If the "answer" is not "false" I want to wait like 20 seconds and do this request again to check if its now something else than "false".

I found many alike questions but after two hours I still can't figure out how to do that. Main problem is the "sleeping" for 20 seconds. If I dont't do that I get too many recursions if calling a function around the ajax-call when the answer comes.

Like:

function doCall( jobId , test) {
   if (test == "false") {
       $.get( "GetJobResult", { jobId: jobId }, function( answer ) {
            // how to wait here?
            doCall( jobId, answer );
        });
    }
}

I am a little bit stuck here. Can anyone help me? Thanks alot!

Edit: I already tried setTimeout like this:

function doCall( jobId , test) {
       if (test == "false") {
           $.get( "GetJobResult", { jobId: jobId }, function( answer ) {
                setTimeout(
                    doCall( jobId, answer ),
                    20000);
            });
        }
}

Upvotes: 0

Views: 36

Answers (2)

Tomas Venere
Tomas Venere

Reputation: 1

You can use console.time (non-standard)

console.time('someFunction');

someFunction(); // run whatever needs to be timed in between the statements

console.timeEnd('someFunction');

Note: The string being pass to the time() and timeEnd() methods must match (for the timer to finish as expected).

Let me know if that was the question :)

Upvotes: 0

Omar Shehata
Omar Shehata

Reputation: 1054

Have you looked into using setTimeout? That's how you would execute a function after waiting X milliseconds. So if you wanted to wait 5 seconds, you would do:

setTimeout(function(){ doCall( jobId, answer ); }, 5000)

The 5000 there is 5000 milliseconds. Does that help?

Edit: Just to clarify, the first argument in setTimeout has to be a function. So another way you could do this is:

setTimeout(doCall,5000)

But there's a problem here. setTimeout doesn't know what arguments you want. Instead we can create a new function that calls the doCall with the correct arguments:

var delayedCall = function(){
  doCall(jobId,answer)
}
setTimeout(delayedCall,5000)

That should work, and that's the same thing as:

setTimeout(function(){ doCall( jobId, answer ); }, 5000)

Except now we're creating a nameless function and passing it in at the same time.

Upvotes: 1

Related Questions