0

I'm currently using a light javascript library to make ajax calls. The library is 'jx'.

And it works fine. But I would like to add a timeout in order to stop the ajax call if there is no response after a certain time. I looked around and it doesn't seems there is a timeout parameter like with jquery...

Is there a way to implement a timeout thanks to a pure javascript? Like this :

timer = setTimeout('function{stop the call}', 20000);
jx.load(url, function(data){ 
        // get the data
        clearTimeout(timer);
        }

I tried that and it's not working well ... is there an other way to do that? Or to make the ajax call syn

5
  • 1
    Fix your code. Instead of 'function{stop the call}' it should be function() { stop the call }. Also, I would put the timeout after the ajax call. Commented Aug 28, 2012 at 17:53
  • The timeout after the ajax call? why? and at the end of the timer how can I stop the call? Commented Aug 28, 2012 at 18:00
  • The lib you're using doesn't have a cancel handler, so You won't be able to do it with this library, sry. And, I guess it wouldn't really matter where you put the setTimeout, it's just a personal preference. Commented Aug 28, 2012 at 18:04
  • Take a look at this: stackoverflow.com/questions/8279035/… Commented Aug 28, 2012 at 18:07
  • @PitaJ see my answer, it seems the library stores the XMLHttpRequest object into a http variable. Commented Aug 28, 2012 at 18:08

1 Answer 1

2

If this is the library you're using, it seems to be possible:

var xhr = jx.init();
var timer = setTimeout(function(){ 
    if(xhr && xhr.abort) xhr.abort();
}, 20000);

jx.load(url, function(data){ 
    clearTimeout(timer);
});
Sign up to request clarification or add additional context in comments.

8 Comments

Yes I'm using this library :) I'm gonna try that right now! Thanks you!
I just added the code you pasted me. It seems like it never calls jx.http.abort(). So I get my error message thanks to the timer and then I get the response from the ajax call.
Looked at jx source again, and it seems I got it wrong the first time. Could you try the updated code above?
@GuillaumeleFloch Are you sure you're using the latest version (3.01A)? jx.init() is supposed to return the xhr object, but in the line by line explanation they seem to use 3.00A, and init returns undefined.
I'm gonna update the version I think I run an oldest version ... Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.