2017-02-20 5 views
0

私のコードでAJAX呼び出しを行っています。私が望むのは、毎分20秒でAJAXコールを叩くことです。これは私が作っているAJAXリクエストです。毎分20秒にAJAXコールを作成します

setInterval(function(){ 
    $.ajax({ 
     url: url, 
     headers: { 'x-cyclops-ajax': 'yes' }, 
     method: 'POST', 
     dataType: 'json', 
     success: function(data) { 
      var chart = $('#container').highcharts(); 
      var keys = Object.keys(data["histData"]); 
      $("#main-div").empty(); 
      for(var i=0; i< keys.length; i++) { 
       chart.series[i].setData(data["histData"][keys[i]]["histFailure"], true); 
       $('#main-div').append('<div class="homepage-availability-inner-div"><h1 class="homepage-availability-text"> ' + keys[i] + ': <span class="dashboard-success">' + data["availData"][keys[i]] + ' </span> </h1></div>'); 
      } 
      chart.xAxis[0].setCategories(data["histKeys"]); 
      console.log("Data:" + JSON.stringify(data["availData"])); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log("Did not hit the AJAX call"); 
     } 
    }); 
}, 5000); 

助けてください。あなたがしなければならないでしょう、...

+2

〜20000の範囲を参照してください。良いアイデアは$を作成しないと思ってください。setintervalの下にあるajaxは非同期です –

+2

'setInterval' BTWで非同期メソッドを使用することは完全に有効です。これは長いポーリングと呼ばれます。その返答が順番に返ってこないかもしれないことに留意してください。 – Liam

+0

ここで質問は正確に何ですか?これは機能しませんか?何? – Liam

答えて

4

あなたは午後01時のように20秒でのみ意味場合:、13時01分:、午前13時02分このような何か:それは20日セコある場合

// the interval can be set lower depending on the use case, to be more accurate 
 
// Warning a too low interval setting might kill the performance of the browser/client, 
 
// and execute the ajax multiple times, if the milliseconds are not considerate 
 
let interval = 1000; 
 

 
// the function is called (about) every second, 
 
// so approximately 60 times per minute and executes the ajax call only once. 
 
setInterval(
 
    function(){ 
 
    let now = new Date(); 
 

 
    // should only fire, if it is the 20th Second in the current minute 
 
    if(now.getSeconds() === 20){ 
 
     //ajax call 
 
     console.info(now); 
 
    } 
 
    }, interval 
 
);

コードは、毎秒をチェックnd。パフォーマンスは、クライアントのために少し重いかもしれませんが、いくつかの呼び出しを行うことはありますが、機能します。それがヒット以上間隔の長さの後に、inertvalを変更する、またはその代わりsetTimeoutを使用して、そして、自己それを呼び出すために次の時間を計算して最適化することができ
:ちょうど考える

ところであなたはまた、ミリ秒を取得したい場合は、下の間隔を置いてもnow変数のgetMilliseconds()機能を照会しなければならないが、これはおそらく、クライアントのパフォーマンスを殺す を.: 。ここ

オプション(just4fun):
あなたが少なくsetInterval呼び出しを行いたい場合は、近くに取得するための設定時間を微調整する方法を、setTimeoutを使用して再帰的関数を呼び出し、「問題は」である可能性がありそれを逃さずに20秒。ここで

から開始するように、小さな基本的な例である:
(はいコードは非常に最適化されておらず、より良い構造化されたかもしれないが、私はそれが大まかなアイデアを与える願っています)

// the 20th Second, when the ajax call should execute 
 
const selectedSecond = 20; 
 

 
// can be tweaked to hit closer to 20th Second (ms) 
 
let shortInterval = 400; 
 

 
// depence on the size less calls are made 
 
let safetyBuffer = 2; 
 

 
// helper Variable, 60 Seconds 
 
let sixtySeconds = 60; 
 

 
// timeout value which is set dynamic, first time will execute "immediately" 
 
let currentTimeout = 0; 
 

 
function timeoutHandler(){ 
 
    // gets current Time 
 
    let now = new Date(); 
 
    let seconds = now.getSeconds(); 
 
    if(seconds === selectedSecond){ 
 
     // **** here the ajax call should go **** 
 
     console.info("ajax Called!!"); 
 
     // sets the next timeout 58s later, not to miss the 20th Second 
 
     currentTimeout = (sixtySeconds - safetyBuffer) * 1000; 
 
    }else if(seconds > selectedSecond){ 
 
     // sets the next timeout to 2s beforethe 20th Second 
 
     currentTimeout = (sixtySeconds - safetyBuffer - seconds + selectedSecond) * 1000; 
 
    } else if(seconds < selectedSecond - safetyBuffer) { 
 
     // sets the next timeout to 2s beforethe 20th Second 
 
     currentTimeout = (selectedSecond - safetyBuffer - seconds) * 1000; 
 
    } else { 
 
     // sets the next timeout to shortInterval(=400ms), 
 
     // for the last 2s, it will be more often, to not miss the 20th second 
 
     currentTimeout = shortInterval; 
 
    } 
 
     
 
    // calls the function with the new optimized timeout 
 
    setTimeout(timeoutHandler, currentTimeout);  
 
} 
 

 
// initial call 
 
setTimeout(timeoutHandler, currentTimeout);

+1

これは20秒** **正確に**で動作しないことに注意してください。 'setInterval'はその期間内に正確に実行される保証はありません。これは、jsスレッドの使用率など、さまざまな要因に基づいて変化します(これはかなり多少あります) – Liam

+0

あなたはライトですが、必要な精度によっては、間隔を狭くしたり、 。私はそれがウェブアプリケーションであることを暗示しています。ここでは、JSスクリプトの実行を長期間ブロックすることはないので、大丈夫です。しかし、それはユースケースに依存します –

+0

@Liam私の使用例は、毎分20秒でページを更新する必要があるということです。しかし、リクエストが行われ、データがまだ戻っておらず、次のリクエストがあった場合はどうなりますか? –

2

連続ループの場合はsetIntervalメソッドを使用できます。現在の秒が20の場合は、ajax呼び出しを行うことができます。コードスニペット:

setInterval(function() { 
    if(new Date().getSeconds() === 20) { 
    // Your ajax call 
    } 
}, 1000); 
関連する問題