Hi

I was wondering if there is a standard way to set a time out for ajax callbacks. The problem seems such an obvious one I know that it will have been solved several times.

I'm using the google maps and google local api's and I want to wrap my ajax calls such that if the servers don't respond within a certain amount of time, then my code can recover and go on with out the information.

I have been thinking about writing a class whose objects would wrap any ajax request in such a way as to behave nicely, but surely this has already been done.

I have tried searching for this information (admittedly not as hard as I should have), but the material seems quite fragmented. If someone could just point me in the right direction with a link then that would be very much appreciated.

Dani AI

Generated

nailed the real problem (the dreaded double-callback) and pointing at a timer was a useful hint. A practical pattern is: where possible actively cancel the request, and always guard the callback so only the first outcome runs. Below are small, reusable patterns that work across common AJAX styles (XHR/jQuery, fetch, JSONP/Google services).

A tiny "run-once" wrapper you can reuse to protect any callback:

function once(fn) {
  var called = false;
  return function() {
    if (called) return;
    called = true;
    fn.apply(this, arguments);
  };
}

Modern fetch with an abortable timeout (works cleanly in browsers that support AbortController):

async function fetchWithTimeout(url, opts, ms) {
  var controller = new AbortController();
  var timer = setTimeout(function(){ controller.abort(); }, ms);
  try {
    var res = await fetch(url, Object.assign({}, opts, { signal: controller.signal }));
    clearTimeout(timer);
    return res;
  } catch (err) {
    clearTimeout(timer);
    if (err.name === 'AbortError') throw new Error('timeout');
    throw err;
  }
}

JSONP and some Google service callbacks cannot be truly aborted. Use a token/ID or the once guard to ignore stale results, and remove the script tag on timeout:

var latestGeocodeId = 0;
function doGeocode(address) {
  var id = ++latestGeocodeId;
  geocoder.geocode({ address: address }, function(results, status) {
    if (id !== latestGeocodeId) return; // ignore stale reply
    // handle results
  });
}

Practical tips: clear timers and delete temporary globals to avoid leaks; prefer library features (jQuery timeout or axios timeout) when available; always assume a callback might still arrive and protect your UI/state with a guard. These patterns work well with Google Maps/Local APIs where you cannot forcibly kill every server-side callback.

Recommended Answers

All 2 Replies

Have u tried using the setTimeout() function?

The setTimeout() is part of the solution but not the whole story.

If the ajax server responds before the timeout then the timeout callback will still fire and we have to deal with this. If the ajax server responds but after the timeout then this will generate a call back which has to be dealt with.

setTimeout() is not enough on its own. I'm sure that there must exist some sort of wrapper class which deals with the possibility of receiving two callbacks (one from the timeout and the other from the ajax server), forwards which ever came first and suppresses the second one.

Thanks anyway

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.