2017-07-27 1 views
0

XMLHTTPリクエストを作成する便利な方法がありますJavascript?送信する前に3秒待っていますか?私は、アレイフルネームXMLHTTPリクエストの遅延

var items = [ 
    { url: "www.google.com/getChocolate", name: "Chocholate"}, 
    { url: "www.google.com/getCake", name: "Cake"}, 
    { url: "www.google.com/getCookie", name: "Cookie"}, 
]; 

for (var i = 0; i < items.length; i++) { 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      var data; 
      data = JSON.parse(xhr.responseText); 
      // processing data here 
     } 
    }; 
    xhr.open("GET", items[i].url, false); 
    xhr.send(); 
    // I somehow have to force to send the request for each item only every 3 seconds 
} 

を持っており、それらのそれぞれのために私は、サーバーからJSONレスポンスを受信したいが、私はあまりにも頻繁にリクエストを送信する場合、それはいつか私を禁止するので、私はすべての3のようにそれらを送信する必要があります応答を待ち、応答を処理して新しい応答を開始します。 私はそれを同期させなければならないと思うので、すでに虚偽の議論をxhr.openに入れています。

+0

'setTimeout'はあなたが探しているものです。 –

+0

* "それを同期させる必要があります" * ...決してこれを行うことはありません!それはUI全体をブロックして、恐ろしい練習であるので非難されます – charlietfl

+0

リクエストに 'setTimeout'をループで追加すると、指定された時間だけ待ち、すべてのアイテムのリクエストを一度に送信します。 1。 –

答えて

0

H Iの友人、

私はちょうどあなたのポストを見て、私はあなたが要求キューをしたいということを理解する - その後の終わりまで次と次の送信3秒後に最初の要求を送信し、完了するために、それを待ちます待ち行列。

私は非常に簡単なクラスRequestRequestManagerを作成しました。

コードを見て、あなたに不明な点がある場合はお知らせください。コメントも読んでみてください。

var items = [{ 
 
    url: "www.google.com/getChocolate", 
 
    name: "Chocholate" 
 
    }, 
 
    { 
 
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cake", 
 
    name: "Cake" 
 
    }, 
 
    { 
 
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cookie", 
 
    name: "Cookie" 
 
    }, 
 
]; 
 

 
/* First prepare array of requests that later will be send */ 
 
var requests = []; 
 
for (var i = 0; i < items.length; i++) { 
 
    requests.push(new Request(items[i].url)); 
 
} 
 

 
/* Initialize the object that will be responsible for 
 
* request sending and process the requests */ 
 
var manager = new RequestManager(requests); 
 
manager.process(); 
 
manager.onSend(function(url, response) { 
 
    /* this code will fire once a request is completed, no matter if success of failed */ 
 
    console.log('request to ' + url + ' completed ....'); 
 
    console.log('----------------------------------------'); 
 
}) 
 

 

 
/** 
 
* This class is a wrapper that will hold the request 
 
* and will be responsible to send it with a delay of 3 seconds 
 
* 
 
* @param {string} url - this is the url which is going to be requested 
 
* @returns {Request} - new Request object 
 
*/ 
 
function Request(url) { 
 
    var that = this, resolve, reject; 
 
    that.url = url; 
 

 
    that.promise = new Promise((res, rej) => { 
 
    resolve = res; 
 
    reject = rej; 
 
    }); 
 

 
    that.xhr = new XMLHttpRequest(); 
 
    that.xhr.onreadystatechange = function() { 
 
    if (that.xhr.readyState == 4) { 
 
     if (that.xhr.status == 200) { 
 
     var data = null; 
 
     try { 
 
      data = JSON.parse(that.xhr.responseText); 
 
      resolve(data); 
 
     } catch (e) { 
 
      reject(e); 
 
     } 
 
     } else { 
 
     reject({ 
 
      statusText: that.xhr.statusText, 
 
      response: that.xhr.response 
 
     }); 
 
     } 
 
    } 
 
    }; 
 

 
    that.send = function() { 
 
    /* send request after 3 seconds */ 
 
    setTimeout(function() { 
 
     that.xhr.open("GET", that.url, true); 
 
     that.xhr.send(); 
 
    }, 3000) 
 

 
    return this; 
 
    } 
 
} 
 

 

 
/** 
 
* This class is responsible for processing all the request 
 
* The main role is to call the Request's send method, 
 
* wait the request to complete and then call the next request from the queue 
 
* until all the requests are processed 
 
* 
 
* @param {Array} requests - this is an array of Request objects 
 
* @returns {RequestManager} new RequestManager object 
 
*/ 
 
function RequestManager(requests) { 
 
    var that = this, 
 
    callback; 
 
    that.requests = requests; 
 

 
    that.onSend = function(cb) { 
 
    callback = cb; 
 
    } 
 

 
    that.process = function() { 
 
    console.log('Starting requests sending .......'); 
 
    doRequestRecursive(that.requests.pop()); 
 
    } 
 

 
    function doRequestRecursive(request) { 
 
    request.send().promise.then(function(data) { 
 
     console.log('request ' + request.url + ' success ...'); 
 
     callback(request.url, data); 
 
    }, function(err) { 
 
     console.log('request ' + request.url + ' failed ...'); 
 
     callback(request.url, err); 
 
    }).then(function() { 
 
     var nextRequest = that.requests.pop(); 
 
     if (nextRequest) { 
 
     doRequestRecursive(nextRequest); 
 
     } 
 
    }); 
 
    } 
 
}

サンプル・コード・スニペットは、あなたのリンクがものを働いていないので、彼らは成功していることを実証するために、ウィキペディアへのリクエストを送信しています。