简体   繁体   中英

How to execute asynchronous code in a loop?

I tried to keep this in a loop but webpage freezes every time I try to keep this in the loop. Any suggestion how to get location live update by this?

function hello(){
   for(var i=0;i<=10;i++){  
      if(i==10){
         call();
         i=0;
     }
}

function call(){
  var settings = {
    "url": "https://pos.ls.hereapi.com/positioning/v1/locate?apiKey=imnotgoingtoshareliveapikeyeveragain",
    "method": "POST",
    "timeout": 0,
    "headers": {
      "Content-Type": "application/json"
    },
    "data": JSON.stringify({"lte":[{"mcc":404,"mnc":49,"cid":231706401}]}),
  };

  $.ajax(settings).done(function (response) {
    console.log(response);
  });
}

Try this one (every 10 seconds will trigger call function):

 function call(){ var settings = { "url": "https://pos.ls.hereapi.com/positioning/v1/locate?apiKey=s_WF6U2g60ucHbmnYIyuieeUWnkT0jshGf4mD33kpwI", "method": "POST", "timeout": 0, "headers": { "Content-Type": "application/json" }, "data": JSON.stringify({"lte":[{"mcc":404,"mnc":49,"cid":231706401}]}), }; $.ajax(settings).done(function (response) { console.log(response); }); } function hello(){ setInterval(function(){ call() }, 10000); }; hello();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Instead of writing two separate functions, you can use setInterval to run every x seconds:

var settings = {
    "url": "https://pos.ls.hereapi.com/positioning/v1/locate?apiKey=s_WF6U2g60ucHbmnYIyuieeUWnkT0jshGf4mD33kpwI",
    "method": "POST",
    "timeout": 0,
    "headers": {
      "Content-Type": "application/json"
    },
    "data": JSON.stringify({"lte":[{"mcc":404,"mnc":49,"cid":231706401}]}),
  };

setInterval(function(){ 


 $.ajax(settings).done(function (response) {
    console.log(response);
  });



 }, 10000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM