2015-02-11 104 views
1

我有一個函數使用「post」從服務器獲取數據並對其進行處理。數據量不盡相同,功能可能需要很長時間才能完成(30秒)。我希望重複調用這個函數,但是隻有在它完成前一次迭代之後的10秒鐘。 *函數的結果存儲在全局函數中,並在相同函數的下一次迭代中使用。 我試過setInterval和setTimeout,但是這些似乎都沒有給我我要找的結果。 有什麼想法?完成後10秒重複運行一個函數(JavaScript)

+0

爲什麼setInterval沒有給你想要的輸出?你可以解釋嗎 ? – taesu 2015-02-11 04:08:56

+0

向我們顯示您的代碼,以便我們可以看到最新進展ob – 2015-02-11 04:10:53

+0

@taesu間隔在涉及Ajax請求時不起作用。 OP希望在通話完成和處理後10秒。 – epascarello 2015-02-11 04:13:38

回答

1
function a(){ 
//do stuff 

setTimeout(a, 10000); //has to be at the end of the execution. If you're doing things asynchronously that's a different story. 

} 
0

function setTimeout()可以用於此。但該方法必須首次被調用,然後函數本身再次調用該方法。

function method(){ 

     console.log('method invoked'); 
     setTimeout(method, 10000); 
    } 

    method(); 
2
function foo(){ 
    $.post("test.php", { name: "John", time: "2pm" }) 
     .done(function(data) { 
     // do your stuff with returned data 
     // and call itself again... 
     setTimeout(foo, 10000); 
    }); 
} 

這是不是辦法的工作?

-1
function Test() 
{ 
    //Your code here 

setTimeout(Test(),10000); 
//Its used to set time interval after your iteration is run 

} 
+1

歡迎來到[so]。請注意,有多個答案已經說過同樣的事情,而且這個代碼無法正常工作,因爲'Test'在函數中立即被調用。 – 2015-02-11 10:37:47

0
var $id = 1; 
var Interval ; 
$(function(){ 
     callAjax();//Starts Interval 
}); 

functoin callAjax() 
{ 
Interval = setInterval(function() { 
      try { 
       if($id > 0) 
       { 
       $.ajax({ 
        url: _MyUrl + $id, 
        success: function (calbkData) { 
         $id = 0; 
         if (parseInt(calbkData.id) > 0) { 
          $id = calbkData.id; 
          OpenMsg(calbkData.id); 
         } 
        }, 
        global: false, // this makes sure ajaxStart is not triggered 
        dataType: 'json' 
        //,complete: longpoll 
       }); 
       } 
      } catch (e) { 
      //  alert(e); 
      } 

     }, 10000); 
} 

這是工作非常細,對我來說。

相關問題