skip to Main Content

I have some Javascript code that grabs data from a server in a jQuery ajax call, and it seems to always trigger the success callback, even when it didn’t get the proper data. The error callback never gets triggered as its supposed to. I want to set a time limit on the success so if the data isn’t grabbed quick enough, an error is thrown. How might I do this?

3

Answers


  1. Did you tried function?
    setTimeout();

    Usage :

    setTimeout(function(){
        // a function you want to do
    }, timeLimit);
    //timeLimit : time as miliseconds. 2000 means 2 seconds.
    // example : 
    setTimeout(function(){
        alert("Hello World");
    },2000);
    
    Login or Signup to reply.
  2. Set the timeout property on the object.

    const url = "https://cors-anywhere.herokuapp.com/http://example.com/";
    
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.timeout = 5; // This is very small to demo it!
    xhr.addEventListener("load", () => console.log("Loaded!"));
    xhr.addEventListener("timeout", () => console.log("Timed out!"));
    xhr.addEventListener("error", () => console.log("Error!"));
    xhr.send();
    Login or Signup to reply.
  3. In ajax:

     $.ajax({
    success: function(data){
        //Success code
    },
    url: "your_url",
    error: function(data){
        //Error code
    },
    timeout: 6000 // sets timeout to 6 seconds
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search