Skip to content

Instantly share code, notes, and snippets.

@rnaffer
Created October 27, 2015 18:29
Show Gist options
  • Save rnaffer/4c952871bd11c60c1fc2 to your computer and use it in GitHub Desktop.
Save rnaffer/4c952871bd11c60c1fc2 to your computer and use it in GitHub Desktop.
Ejemplo del patrón de diseño "Asynchronous Execution" con explicación.
// Las ejecuciones muy largas de codigo JavaScript tienden a bloquear el UI y dejar al navegador sin responder,
// sobre todo cuando se emplean bucles. Este patron emplea temporizadores para evitar precisamente este problema.
// Es un inconveniente bastante común en dispositivos móviles.
var buffer = function( items, iterFn, callback ) {
var i = 0,
len = items.length;
setTimeout(function() {
var result,
start;
// Se emplea la diferencia de tiempo que existe entre bucles para asegurar que no exeda los 50ms
for ( start = +new Date(); i < len && result !== false && ((+new Date()) - start < 50); i++ ) {
result = iterFn.call( items[i], items[i], i );
}
// arguments.callee es una forma de hacer referencia a la misma función, osea, recursividad.
if ( i < len && result !== false ) {
setTimeout( arguments.callee, 20 );
} else {
callback( items );
}
}, 20 );
}
$.get( '/home/data', function( result ) {
var html = '';
buffer( result, function( item ) {
html += '<li>' + item + '</li>';
}, function() {
$('ul').append( html );
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment