0

In the below code , I loop through each domains and do some operations via jQuery GET function.The Loop is synchronous. How to make each loop wait 5 seconds before it perform next GET request.

 jsons = ["123.com","234.com","456.com"]


    jQuery.each(jsons, function(key,ele) {
    var maindomain = ele; 
    var apis= "https://api.panel.com/search?q="+maindomain;
    $.get(apis, function(source) { 

    if(source == "yes")
    {
    $.get("https://database.com/update.php?domain="+maindomain, function(response) { 
    console.log("successs");
    });
    }

    //SLEEP 5 seconds Here
    });
3
  • 1
    have you tried setTimeout()? Commented Mar 1, 2016 at 6:57
  • why do not you use closure Commented Mar 1, 2016 at 6:58
  • 1
    Possible duplicate of jQuery ajax inside a loop problem Commented Mar 1, 2016 at 7:01

1 Answer 1

2

You could use .queue(), $.when() , setTimeout(), .dequeue()

var jsons = ["123.com","234.com","456.com"];

$({}).queue("requests", jsons.map(function(request) {
  return function(next) {
    // do ajax stuff
    $.get("https://api.panel.com/search?q=" + request)
    .then(function(source) {
       if (source === "yes")
       return $.get("https://database.com/update.php?domain=" + maindomain)
    })         
    .then(function() {
      // call `next` function after `5000ms` timeout
      setTimeout(next, 5000)
    })
  }
})).dequeue("requests")

var jsons = ["123.com","234.com","456.com"], res = [];

var fn = function(arg) {
  return $.Deferred(function(d) {
    d.resolve([arg, "success", {}])
  }).then(function(data) {
    res.push(data); return data
  })
}

$({}).queue("requests", jsons.map(function(request) {
  return function(next) {
    // do ajax stuff here
    fn(request).then(fn.bind(null, request))
    .then(function() {
      console.log(res)
      // call `next` function after `5000ms` timeout
      setTimeout(next, 5000)
    })
  }
})).dequeue("requests")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Sign up to request clarification or add additional context in comments.

3 Comments

database.com/update.php?domain=" + maindomain should run only after the first get request is completed
plus one , Hi , How Can I add error handling to this snipper
@Vishnu You should be able to add .fail() chained to second .then()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.