Backbone.js: define timeout for Backbone.sync implementation
Asked Answered
A

1

12

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?

Antecedence answered 18/1, 2013 at 17:23 Comment(1)
"I know all requests lead to Backbone.sync" - I think the more important fact here is that all events lead to $.ajax()! Solves lots of questions regarding backbone fetch() and sync() requests.Busybody
A
22

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});
Amide answered 18/1, 2013 at 18:49 Comment(2)
I see, so there are some more options which can be passed to tne sync method which are not documented. btw can I also pass something such as {complete : functioname} ? In case I want to implement long polling.Antecedence
You can pass any option you want, there is no validation. Backbone uses some of them, adds some more to it, and then passes it to jQuery.ajax, which is documented also. You can set complete handler if you wish.Amide

© 2022 - 2024 — McMap. All rights reserved.