14 June, 2011

Monitoring the execution of asynchronous JavaScript callbacks

In JavaScript sometimes it's useful to know if an asynchronous callback function was called, how many times and if it completed or failed. Of course you could implement it by changing some state in the outside scope, but this means adding code to the function and it won't work for existing 3rd party code.
I've written a small jQuery extension, jquery.monitor.js, (there is no actual jQuery dependency in the implementation by the way) which creates a wrapper around the callback function that keeps the latest call status and history in a property called monitor.

Example:

var m = $.monitor(mycall);//wrap the callback, m.monitor.status is 'unused'
$.getJSON("my.json", m()); //calling m() prepares a callback and sets m.monitor.status to 'queued'
$.getJSON("another.json", m());


When the callback starts, m.monitor.status will be set to 'called' and when it completes it will become 'completed' or 'failed' if it raised an exception.

In addition there are 4 counters for the history of each state: monitor.queued, monitor.called, monitor.completed and monitor.failed (in the example above m.monitor.queued and m.monitor.called will be 2 and the sum of m.monitor.completed and m.monitor.failed will be equal to 2).
To check if all queued calls have completed use the m.isPending method (for this to work the result from calling m() should not be reused for consecutive callbacks!!!) and to reset the monitor use the m.clearMonitor method.

0 comments: