用setTimeout 代替 setInterval實時拉取數據


  在開發中,我們常常碰到需要定時拉取網站數據,如:

setInterval(function(){
   $.ajax({
       url: 'xx',
       success: function( response ){
          // do something with the response
       }
   });
}, 5000);

請思考下此寫法有什么弊端?

能想到情況是:如果接口異常了,程序仍然會間隔5000ms抓取數據。換句話說,我們不能捕獲到異常,並做一些合理的調整。

所以我們換個寫法:

// new hotness
(function loopsiloop(){
   setTimeout(function(){
       $.ajax({
           url: 'xx',
           success: function( response ){
               // do something with the response

               loopsiloop(); // recurse
           },
           error: function(){
               // do some error handling.  you
               // should probably adjust the timeout
               // here.

               loopsiloop(); // recurse, if you'd like.
           }
       });
   }, 5000);
})();

如果我們能捕獲到異常,可以限定異常大於10次時,我們將不再拉取數據,並且在異常 》1 且 《10 時,我們可以適當將間隔拉大,讓服務器有休息的時間。

程序稍微修改成:

var failed = 0; 

(function loopsiloop( interval ){
   interval = interval || 5000; // default polling to 1 second

   setTimeout(function(){
       $.ajax({
           url: 'foo.htm',
           success: function( response ){
               // do something with the response

               loopsiloop(); // recurse
           },
           error: function(){

               // only recurse while there's less than 10 failed requests.
               // otherwise the server might be down or is experiencing issues.
               if( ++failed < 10 ){

                   // give the server some breathing room by
                   // increasing the interval
                   interval = interval + 1000;
                   loopsiloop( interval );
               }
           }
       });
   }, interval);
})();

這樣是不是靈活多了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM