为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

RISEBY 2021-05-02 17:11:42
对于这个问题,我一点都不熟悉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);
查看完整描述

2 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

您可以使用setTimeout并等待请求完成来连续调用该函数


var timeoutPtr;


/**

 * Execute a request, can take DELTA miliseconds

 */

function executeRequest() {

  return new Promise((resolve) => {

    var request = new XMLHttpRequest();


    // ...


    request.onload = function() {

      // ...


      resolve();

    };


    request.send();

  });

}


/**

 * Execute the request, when it's over, wait 2s and execute it again

 * and again, and again...

 */

function executeRequestInARow() {

  // In case you call executeRequestInRow multiple time

  clearTimeout(timeoutPtr);


  executeRequest()

    .then(() => {

      timeoutPtr = setTimeout(function() {

        executeRequestInARow();

      }, 2000);

    });

}


executeRequestInARow();


查看完整回答
反对 回复 2021-05-13
  • 2 回答
  • 0 关注
  • 214 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信