未加星标

A Recursive setTimeout Pattern

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Monday, October 18, 2010

Colin Snover wrote a good article about why he thinks setInterval is considered harmful:

setInterval ignores errors . If an error occurs in part of your code, it'll be thrown over and over again. setInterval does not care about network latency . When continuously polling a remote server for new data, the response could take longer than the interval amount, resulting in a bunch of queued up AJAX calls and an out-of-order DOM.

The solution is to recursively call a named function within setTimeout , which guarantees that your logic has completed before attempting to call it again. At such, this also doesn't guarantee that your logic will occur on a regular interval. If you want new data every 10 seconds and it takes 15 for your response to come back, you're now behind by 5 seconds. Colin notes that you can adjust your delay if need be, but you shouldn't really care as javascript timers are not accurate to begin with.

So how to do this? Consider an AJAX poller as this is a common use case:

// old and busted - don't do this setInterval(function(){ $.ajax({ url: 'foo.htm', success: function( response ){ // do something with the response } }); }, 5000); // new hotness (function loopsiloop(){ setTimeout(function(){ $.ajax({ url: 'foo.htm', 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); })();

I'm doing three things here:

Declaring a function loopsiloop that is immediately invoked (notice the parens at the end). Declaring a timeout handler to fire after 5 seconds. Polling the server inside the timeout, which upon either success/failure will call loopsiloop and continue the poll.

It's also important to remember that DOM manipulation takes time as well. With this pattern we're guaranteed that the response will be back from the server AND the DOM will be loaded with new content before attempting to request more data.

It's wise to add error handling in cases when the server experiences latency issues or becomes unresponsive. When requests fail, try increasing the polling interval to give the server some breathing room, and only recurse when under a fixed amount of failed attempts:

// keep track of how many requests failed 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); })();

But the success handler can still fire even if the response is an error, the astute reader might say. For that, let's break out the error logic from its handler so it can also be used in the success callback:

// keep track of how many requests failed var failed = 0, interval = 5000; function errorHandler(){ if( ++failed < 10 ){ // give the server some breathing room by // increasing the interval interval = interval + 5000; loopsiloop( interval ); } } (function loopsiloop( interval ){ setTimeout(function(){ $.ajax({ url: 'foo.htm', success: function( response ){ // what you consider valid is totally up to you if( response === "failure" ){ errorHandler(); } }, error: errorHandler }); }, interval); })();

Good, except that now we have a bunch of floating variables and functions. Ugly, amirate? Let's organize this into an object literal:

var poller = { // number of failed requests failed: 0, // starting interval - 5 seconds interval: 5000, // kicks off the setTimeout init: function(){ setTimeout( $.proxy(this.getData, this), // ensures 'this' is the poller obj inside getData, not the window object this.interval ); }, // get AJAX data + respond to it getData: function(){ var self = this; $.ajax({ url: 'foo.htm', success: function( response ){ // what you consider valid is totally up to you if( response === "failure" ){ self.errorHandler(); } else { // recurse on success self.init(); } }, // 'this' inside the handler won't be this poller object // unless we proxy it. you could also set the 'context' // property of $.ajax. error: $.proxy(self.errorHandler, self) }); }, // handle errors errorHandler: function(){ if( ++this.failed < 10 ){ // give the server some breathing room by // increasing the interval this.interval += 1000; // recurse this.init(); } } }; // kick this thing off poller.init();

And there you have it a safe, basic, and organized AJAX poller to get you started.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaScriptJava
分页:12
转载请注明
本文标题:A Recursive setTimeout Pattern
本站链接:http://www.codesec.net/view/482658.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(24)