与使用window.setInterval()相比,有比这里更干净的方法来重新运行api调用吗?

对于这个问题,我一点都不熟悉javascript或编程。但是,尽管如此,我确实设法完成了艰巨的任务。我想知道,是否有适当或更实际的方式来做到这一点?预先感谢您的帮助。如果有人想知道的话,这是用于队列管理系统的。


var requestURL = 'https://api.qminder.com/v1/tickets/search/?rest-api-key=APIKEY'

var request = new XMLHttpRequest();

request.open('GET', requestURL);

request.responseType = 'json';

request.send();

request.onload = function() {

  var customers = request.response;

  console.log(customers.data)


  x = []


  for (var i = 0; i < customers.data.length; i++) {


    console.log(customers.data[i].status);


    if (customers.data[i].status == "NEW") {

      x.push(customers.data[i])

    }

  }


  var html = '<ul>';

  for (var i = 0; i < x.length; i++) {

    html += '<li>' + x[i].firstName + '</li>';

    console.log(x[i].firstName)

  }

  html += '</ul>';

  document.getElementById("names").innerHTML = html;


}



window.setInterval(function() {

  var requestURL = 'https://api.qminder.com/v1/tickets/search/?rest-api-key=APIKEY'

  var request = new XMLHttpRequest();

  request.open('GET', requestURL);

  request.responseType = 'json';

  request.send();

  request.onload = function() {

    var customers = request.response;

    console.log(customers.data)


    x = []


    for (var i = 0; i < customers.data.length; i++) {


      console.log(customers.data[i].status);


      if (customers.data[i].status == "NEW") {

        x.push(customers.data[i])

      }

    }


    var html = '<ul>';

    for (var i = 0; i < x.length; i++) {

      html += '<li>' + x[i].firstName + '</li>';

      console.log(x[i].firstName)

    }

    html += '</ul>';

    document.getElementById("names").innerHTML = html;


  }

}, 2000);


RISEBY
浏览 219回答 2
2回答

子衿沉夜

您可以使用setTimeout并等待请求完成来连续调用该函数var timeoutPtr;/**&nbsp;* Execute a request, can take DELTA miliseconds&nbsp;*/function executeRequest() {&nbsp; return new Promise((resolve) => {&nbsp; &nbsp; var request = new XMLHttpRequest();&nbsp; &nbsp; // ...&nbsp; &nbsp; request.onload = function() {&nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; resolve();&nbsp; &nbsp; };&nbsp; &nbsp; request.send();&nbsp; });}/**&nbsp;* Execute the request, when it's over, wait 2s and execute it again&nbsp;* and again, and again...&nbsp;*/function executeRequestInARow() {&nbsp; // In case you call executeRequestInRow multiple time&nbsp; clearTimeout(timeoutPtr);&nbsp; executeRequest()&nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; timeoutPtr = setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; executeRequestInARow();&nbsp; &nbsp; &nbsp; }, 2000);&nbsp; &nbsp; });}executeRequestInARow();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript