It's something I usually do; for example, in this hypothetical function
function fetchData( url, args, callback, opts ) {
var ajax = webix.ajax( );
...
function success( text, data, xhr ) {
var response;
...
setTimeout( function( ) { callback( response ); }, 0 );
}
function failure( ) {
var response;
...
setTimeout( function( ) { callback( response ); }, 0 }
}
}
It would be a function to make AJAX calls, check for possible errors, and return an output in a common format, whether there were errors or not.
Since it is a function that makes a AJAX call, it is asynchronous. Therefore, I can not directly return the value, so I use the callback
argument. When I have something to return, I call that function.
The logic I've always used is:
Since Javascript is based on events, and these are not processed while we are executing code, it is best to finish the code as soon as possible .
Therefore, instead of doing:
callback( response );
That would increase the time of continued execution of my code, I do this another:
setTimeout( function( ) { callback( response ); }, 0 );
With which, an event would be created in the queue to make the call to callback( )
. My Javascript code ends, and the browser can continue processing its little things .
Am I correct in doing so? Is there any possible hidden side effect and what do you expect to crouch to attack me at any time?