In functions of answers to callbacks, which in turn call another, is it okay to exit with setTimeout?


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?

asked by Trauma 28.09.2017 в 06:55

1 answer


Your approach is correct and does not have any impact beyond the overload 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 make calculations very heavy that consume a lot of CPU, such as encryption / decryption of a very long text, compression / decompression of files, image treatments ... you will not notice improvement.

There is a possible side effect that you could easily mitigate, and that you can see with a simple example:

$(function () {

  function callback() {
  $('#btn2').click(function () {
  $('#btn3').click(function () {
<script src=""></script>
<button id="btn1">Botón 1</button>
<button id="btn2">Botón 2</button>
<button id="btn3">Botón 3</button>

As you can see, jQuery always calls the "callback" function ensuring that the context is the element that has received the event, and this is lost when using setTimeout unless you explicitly set it.

Conclusion : possible side effects are minimal and easily avoidable.

A related question in SO in English, with a fairly complete answer, you can find it here

answered by 28.09.2017 / 09:55