avoliva avoliva - 5 months ago 11
jQuery Question

Call a function if request time has exceeded 500ms

Is there a way to call a function, for example, one that inserts a loading GIF, if an ajax request has taken more than a specified length of time? It also shouldn't be called if the request finishes before that time is up.

I'm thinking maybe using a

setTimeout
for 500ms and then destroying it in the success callback, meaning it may not run if it's destroyed before 500ms is over.

EDIT: I don't want the request to fail after this 500ms. It should keep continuing to run.

Answer

Keep ajax request and call a function after 500ms

To execute the function after 500ms and keep the request alive use setTimeout()

$.ajax({
    url: "hodor.html",
    error: function () {
        clearTimeout(timeoutID);

    },
    success: function () {
        clearTimeout(timeoutID);

    }
});

var timeoutID = setTimeout(function () {
    console.log("The timeout passed");
}, 500);

Abort ajax request and call a function after 500ms

Use ajax built in timeout handling. Set timeout in ms and error callback function. Identify timeouts in the callback with t:

$.ajax({
    url: "hodor.html",
    timeout: 500,
    error: function(x, t, m) {
        if (t === "timeout") {
            // Timeout
        } else {

        }
    },
    success: function(){

    }
});