Wikipedia para siempre
ShareCode
Permalink: http://www.treeweb.es/u/974/ 01/02/2011

ShareCode

1 /*/////////////////////////////////////////////////////////////////////////////2  //3  AJAX DEFINITION (BEGIN) //4  */5 /**6  * Description: Manage ajax connections with a queue model.7  * Author: gerardooscarjt@gmail.com8  * Date: 2013/31/019  * Typical use:10 11 var ajax = new Ajax();12 ajax.setUrl('http://example.com/path');13 ajax.setMethod('post');14 ajax.setData({'name':'a','age':'22'};15 ajax.callback.done = function(xhr) {16  // ...17 };18 ajax.callback.error = function(xhr) {19  // ...20 };21 ajax.send();22 23 */24 var Ajax = function() {25  26  Ajax.prototype.requests.push(this);27  28  this._id = Ajax.prototype.id_generator;29  Ajax.prototype.id_generator++;30  31  this.callback = {32  done:null,33  error:null,34  progress:null,35  presend:null36  };37  38  this._method = 'get';39  this._async = true;40  this._url = '';41  this._data = null;42  this._retries = 3;43  this._xhr = null;44  45 }46 47 Ajax.prototype.requests = [];48 Ajax.prototype.queue = [];49 Ajax.prototype.id_generator = 0;50 Ajax.prototype.concurrency_limit = 4;51 52 /// METHOD ///53 Ajax.prototype.setMethod = function(method) {54  if (!this.isQueued())55  this._method = method;56 };57 Ajax.prototype.getMethod = function(method) {58  return this._method;59 };60 61 /// URL ///62 Ajax.prototype.setUrl = function(url) {63  if (!this.isQueued())64  this._url = url;65 };66 Ajax.prototype.getUrl = function() {67  return this._url;68 };69 70 /// DATA ///71 Ajax.prototype.setData = function(data) {72  if (!this.isQueued())73  this._data = data;74 };75 Ajax.prototype.getData = function () {76  return this._data;77 };78 79 /// IS QUEUED ///80 Ajax.prototype.isQueued = function () {81  return Ajax.prototype.queue.indexOf(this) > -1;82 };83 84 Ajax.prototype.send = function() {85  if (!this.isQueued()) {86  //logger.log(this._id + ' no está en la cola: encolando...');87  ajax_stats[this._id+'.'+this._retries] = {'delay':NaN,'waiting':NaN,'request':NaN,'server_delay':'undefined','status':'queued'};88  ajax_stats[this._id+'.'+this._retries].delay = new Date().getTime();89  Ajax.prototype.queue.push(this);90  Ajax._move();91  } else {92  //logger.log('ya está en la cola'); 93  }94  logger.show();95 };96 97 /**98  * Returns true if abort has been performed99 */100 Ajax.prototype.abort = function() {101  if ( null != this._xhr && this._xhr.readyState != 4) {102  // The request is on the way. It must be cancelled103  ajax_stats[this._id+'.'+this._retries].request = new Date().getTime();104  ajax_stats[this._id+'.'+this._retries].status = 'aborted';105 106  this._xhr.abort();107  delete this._xhr;108  this._xhr = null;109  this._retries--;110  Ajax.prototype.concurrency_limit++;111  return true;112  }113  return false;114 };115 116 117 /// STATIC METHODS ///118 119 // Abort all current requests120 Ajax._abort_all = function() {121  for (var k in Ajax.prototype.requests) {122  var a = Ajax.prototype.requests[k];123  a.abort() && a.send();124  }125 };126 127 /* Move queue */128 Ajax._move = function() {129  130  if (window.navigator.onLine) {131  while (Ajax.prototype.concurrency_limit > 0 && Ajax.prototype.queue.length > 0) {132  var a = Ajax.prototype.queue.shift();133  ajax_stats[a._id+'.'+a._retries].status = 'unqueued';134  a._send();135  Ajax.prototype.concurrency_limit--;136  }137  }138 };139 140 /// PRIVATE METHODS (I WOULD LIKE) ///141 Ajax.prototype._send = function() {142  var that = this;143  144  //logger.log('Send request for '+this._id);145  146  this._xhr = new XMLHttpRequest({mozSystem:true});147  148  this._xhr.open(this._method, this._url, this._async);149  150  this._xhr.onreadystatechange = function(event) {151  if(null != that._xhr && that._xhr.readyState == XMLHttpRequest.DONE) {152  ajax_stats[that._id+'.'+that._retries].status = 'done';153  ajax_stats[that._id+'.'+that._retries].request = new Date().getTime();154  ajax_stats[that._id+'.'+that._retries].server_delay = that._xhr.responseText;155  Ajax.prototype.concurrency_limit++;156  Ajax._move();157  }158  };159  160  this._xhr.onerror = function(event) {161  ajax_stats[that._id+'.'+that._retries].status = 'error';162  Ajax.prototype.concurrency_limit++;163  that._retries--;164  if (that._retries > 0)165  that.send();166  Ajax._move();167  };168  169  this._xhr.send();170  ajax_stats[this._id+'.'+this._retries].waiting = new Date().getTime();171  ajax_stats[that._id+'.'+that._retries].status = 'sent';172  173 };174 175 // Initialize onLine and offLine events176 window.addEventListener('online', function() {177  Ajax._move();178 }, true);179 180 window.addEventListener('offline', function() {181  Ajax._abort_all();182 }, true);183 184  /*185  AJAX DEFINITION (END) //186  //187 /////////////////////////////////////////////////////////////////////////////*/188 189 190 191 var ajax_stats_start = new Date().getTime();192 var ajax_stats = {};193 var line_status = [];194 195 196 197 198 window.addEventListener('load', function(){199  //test1(); 200  201  // Initialize onLine and offLine events202  window.addEventListener('online', function() {203  line_status.push(new Date().getTime());204  }, true);205  206  window.addEventListener('offline', function() {207  line_status.push(new Date().getTime());208  }, true);209  210  211  log_chart = logger.log('CHAT WILL BE RENDERED HERE');212  213 }, true);214 215 216 /**217  * Launch 20 ajax calls218 */219 function test1() {220  221  ajax_stats_start = new Date().getTime();222  ajax_stats = {};223 224  logger.show();225 226  for (var i=0; i<20; i++) {227  var ajax = new Ajax();228  ajax.setUrl('http://www.treeweb.es/request?e='+ajax._id+'&delay=random');229  ajax.callback.done = function(xhr) {230  logger.log('Completed '+ajax._id);231  };232  ajax.send();233  //logger.log('Launched '+ajax._id);234  }235 236  //logger.log(Ajax.prototype.queue);237  238  see_chart();239 }240 241 /**242  * Launch N fast ajax calls243 */244 function test2(n) {245  246  ajax_stats_start = new Date().getTime();247  ajax_stats = {};248 249  logger.show();250 251  for (var i=0; i<n; i++) {252  var ajax = new Ajax();253  ajax.setUrl('http://www.treeweb.es/request?e='+ajax._id+'&delay=0');254  ajax.callback.done = function(xhr) {255  256  };257  ajax.send();258  }259  see_chart();260 }261 262 function see_stats() {263  264  var s = '';265  266  for (k in ajax_stats) {267  s +=268  '<tr>'269  + '<td>' + (k) + ' (server delay ' + ajax_stats[k].server_delay + ')' + '</td>'270  + '<td>' + (ajax_stats[k].delay - ajax_stats_start) + '</td>'271  + '<td>' + (ajax_stats[k].waiting - ajax_stats[k].delay) + '</td>'272  + '<td>' + (ajax_stats[k].request - ajax_stats[k].waiting) + '</td>'273  + '</tr>';274  }275  276  var h = '<tr> <td>id</td> <td>delay</td> <td>waiting</td> <td>request</td> </tr>';277  s = '<table>' + h + s + '</table>';278  279  logger.log(s);280  logger.show();281 }282 283 var log_chart = null;284 285 286 function see_chart() {287  288  var ts = new Date().getTime();289  290  // Calc maximum time:291  /*292  var max_t = -1;293  var max_w = 1;294  for (k in ajax_stats)295  if (ajax_stats[k].request > max_t) {296  max_t = ajax_stats[k].request;297  max_w = ajax_stats[k].request - ajax_stats_start;298  }299  */300  301  max_w = ts - ajax_stats_start;302  303  var s = '';304  305  for (k in ajax_stats) {306  307  var delay = ajax_stats[k].delay;308  isNaN(delay) && (delay = ts);309  310  var waiting = ajax_stats[k].waiting;311  isNaN(waiting) && (waiting = ts);312 313  var request = ajax_stats[k].request;314  isNaN(request) && (request = ts);315 316 317  var delay_ms = delay - ajax_stats_start;318  var waiting_ms = waiting - delay;319  var request_ms = request - waiting;320  321  //if ( isNaN(ajax_stats[k].request) ) logger.log('NAAAAN');322  323  var delay_rel = (100 * Math.floor(1000*(delay_ms) / max_w ) / 1000);324  var waiting_rel = (100 * Math.floor(1000*(waiting_ms) / max_w ) / 1000);325  var request_rel = (100 * Math.floor(1000*(request_ms) / max_w ) / 1000);326  327  s += ''328  + '<div class="label">' + (k) + ' (' + ajax_stats[k].status + ') ' + '</div>'329  + '<div class="row">'330  + '<div class="bar bar-delay" style="width:' + delay_rel + '%" title="' + delay_rel + '%">' + delay_ms + 'ms</div>' 331  + '<div class="bar bar-waiting" style="width:' + waiting_rel +'%" title="' + waiting_rel +'%">' + waiting_ms + 'ms</div>'332  + '<div class="bar bar-request" style="width:' + request_rel +'%" title="' + request_rel +'%">' + request_ms + 'ms</div>'333  + '<div class="bar bar-end" ><div></div></div>'334  + '</div>';335  }336  337  // Display seconds338  s += ''339  + '<div class="label"> seconds </div>'340  + '<div class="row">';341  var second_width = (100 * Math.floor(1000*(1000) / max_w ) / 1000);342  var c = 0;343  for (var i = ajax_stats_start+1000; i<ts; i+=1000) {344  c++;345  s += '<div class="bar bar-second" style="width:' + second_width + '%">' + c + '</div>' 346  }347  348  s += '</div>';349  350  s = '<div class="chart">' + s + '</div>';351 352  log_chart.innerHTML = s;353 354  355 356  logger.show();357  if (Ajax.prototype.queue.length > 0)358  setTimeout(function() {359  see_chart();360  }, 500);361 }362 363 
Enlace
El enlace para compartir es: