Tuesday, May 1, 2012

jQuery callbacks apparently repeat on failure?


I seem to be observing at least one case where a callback function passed to a jQuery effect function will execute repeatedly if there's an error while it's executing.



For example, see this JS Fiddle , featuring the following code:




$('#awesome').fadeOut(400,function () {
log('fading out...');
dieInAFire();
});



log appends whatever's passed to it to a div... but dieInAFire doesn't exist. Rather simply stopping execution, however, the anonymous function appears to be getting called over and over, as evidenced by the growing number of appearances of 'fading out...' in the log div.



Is this the expected behavior? If so, why?


Source: Tips4all

2 comments:

  1. It's a known bug. See the report here.

    ReplyDelete
  2. I just submitted a comment on the bug that patrick dw posted.

    Changing the line:

    options.complete.call(elem);


    To:

    setTimeout(function(){
    options.complete.call(elem);
    }, 0);


    Causes the callback to execute asynchronously, and if it will no longer stop execution if it throws any errors. IMO it's better than using a try catch since it doesn't suppress the exception.

    If you want to edit your minified version, and you use the latest jQuery, you can search for e.complete.call(d) and replace it with setTimeout(function(){e.complete.call(d)},0)

    ReplyDelete