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?
Backbone.js: define timeout for Backbone.sync implementation
Asked Answered
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});
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.
$.ajax()
! Solves lots of questions regarding backbonefetch()
andsync()
requests. – Busybody