Kyle example is about chunking data (when is so big) by asynchronous events and make events interleave in the event loop queue, that part i couldn't get:
The example from book:
var res = [];
// `response(..)` receives array of results from the Ajax call
function response(data) {
var chunk = data.splice( 0, 1000 );
res = res.concat(
chunk.map( function(val){
return val * 2;
} )
);
if (data.length > 0) {
setTimeout( function(){
response( data );
}, 0 );
}
}
// ajax(..) is some arbitrary Ajax function given by a library
ajax( "http://some.url.1", response );
ajax( "http://some.url.2", response );
I could not get that part, my mind can not accept that this could make code perform better, wouldn't that cause data from two arrays to interleave, or i just don't understand how event loop work??
It appears that you are correct that there is a potential for misordering of data with multiple ajax calls (and it was very astute of you to notice, +1), with the code posted you could get:
As for the performance aspect of the question, remember that 'performance' isn't just one thing. If by performance you mean 'how long does this block of code take to run' then chunking will lead to worse performance. But this is frontend. 'Performance' is really about user experience, and your Javascript code runs on the main thread. If you have a 10 second operation then your UI is unresponsive for 10 seconds. If you chunk it then the user can still interact with the page while it's running, even if it takes a little longer to complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With