setTimeout does not work
I'm trying to use the setTimeout method without success.
Here is my code:
var x = Titanium.Network.createHTTPClient();
x.setTimeout([25000]);
x.open('POST','http://domain.com');
x.send('data');
x.onerror = function(e)
{
Ti.API.info(e);
};
x.onload = function()
{
/* Some code */
}
The error method is being runned all the time,just after a few seconds.
Here is my error message:
[INFO] {
error = "Error Domain=ASIHTTPRequestErrorDomain Code=2 UserInfo=0x5032cf0 "The request timed out"";
source = [object TiNetworkClient];
type = error;
}
What may be the problem?
3 Answers
-
Mark: I believe Linus is trying to set a timeout on his http request, not create a javascript timer to do his network operation after 25 seconds.
Linus: Looking at the Appcelerator Titanium source in git seems to indicate that your syntax is correct. Try calling setTimeout AFTER your x.open call, as the call to x.open may by allocating a new request and discarding your previous call to setTimeout. I don't know if this will fix your issue, but it's worth a try.
Also, one thing you should note is that by defining your onerror and onload handlers after calling open you've created a race condition where the asynchronous network operation may complete before the function definitions are executed. Definitely want to fix that. So try this:
var x = Titanium.Network.createHTTPClient(); x.onerror = function(e) { Ti.API.info(e); }; x.onload = function() { /* Some code */ } x.open('POST','http://domain.com'); x.setTimeout([25000]); x.send('data');
-
If you want to add a timeout to your
xhr
object i'd suggest doing like this:var xhr = Titanium.Network.createHTTPClient({timeout:25000});
-
The setTimeout syntax is:
setTimeout ( expression, timeout );
so I'd suggest you write a function to do the work you want and then put that function in your setTimeout call like this:
function myWork() { var x = Titanium.Network.createHTTPClient(); // x.setTimeout([25000]); x.open('POST','http://domain.com'); x.send('data'); x.onerror = function(e) { Ti.API.info(e); }; x.onload = function() { /* Some code */ } } setTimeout ('myWork()', 25000);