It's something I do regularly; 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 output in a common format, whether there were errors or not.
Since it is a function that makes an AJAX call , it is asynchronous. Therefore, I can't directly return the value, so I use the callback
. When I have something to return, I call that function.
The logic I've always used is:
Since JavaScript is event based, and events are not processed while we are executing code, it is best to finish the code as soon as possible .
So instead of doing:
callback( response );
That would increase the continuous execution time of my code, I do this other:
setTimeout( function( ) { callback( response ); }, 0 );
This would create an event in the queue to make the call to callback( )
. My Javascript code terminates, and the browser can continue processing its tidbits .
Am I correct in doing so? Is there some possible side effect hidden and waiting to attack me at any moment?
Your approach is correct and has no drawbacks beyond the overhead in the execution queue (which is negligible), although it is generally not necessary: Javascript is not the fastest language in the world, but unless you do very heavy calculations that consume a lot of CPU, such as the encryption/decryption of a very long text, compression/decompression of files, image treatments... you will not notice any improvement.
There is a possible side effect that you could easily mitigate, and that you can see with a simple example:
As you can see, jQuery always calls the "callback" function ensuring that the context is the element that received the event, and the event is lost when using setTimeout unless you explicitly set it.
Bottom Line : Potential side effects are minimal and easily avoidable.
A related question on SO in English, with a fairly complete answer, can be found here