Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: define timeout for Backbone.sync implementation

I'm using backbone on a project of mine, integrated with communication to an external API. I want to use real-time updating of records. Since I don't have access to the main backend of this external application, and they don't provide neither websocket server nor long-polling endpoint, I am basically left with the option of doing regular polling with setInterval and a period of 50 seconds. It has been working quite well. My problem is the edge case. If for some reason the API request hangs, for more than 50 secs, let's say, I'll be triggering a new request right away. That means, 2 hanging requests now, which will add up eventually. Is there a way to set a timeout for the request? I know all requests lead to Backbone.sync, but I was checking the source code and I don't see any feasible way of setting the timeout for the XmlHttpRequest. Is there a way to do this cleanly and without overwriting behaviour? Or are there other solutions/workarounds?

like image 941
ChuckE Avatar asked Jan 18 '13 17:01

ChuckE


1 Answers

Just pass a timeout:milliseconds option in the options argument to fetch. The options get passed directly to jQuery.ajax, which handles the low-level XHR call:

 collection.fetch({timeout:50000});

Alternatively you can set a global timeout for all the requests made by your application by calling jQuery.ajaxSetup in your application startup:

$.ajaxSetup({timeout:50000});
like image 125
jevakallio Avatar answered Oct 12 '22 11:10

jevakallio