Created
October 27, 2015 18:29
-
-
Save rnaffer/4c952871bd11c60c1fc2 to your computer and use it in GitHub Desktop.
Ejemplo del patrón de diseño "Asynchronous Execution" con explicación.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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