Developer Labs

JQuery Plugin: Polling with timeouts

JQuery Plugin: Polling with timeouts

Polls a server resource at specified timeout interval until abortTimeOut is reached with options for testing responses for success.

This was useful for allowing a machine a certain amount of time to wake from hibernate before aborting.

 

 /** 
 * PollingWithTimeouts - Polls a server resource at specified timeout 
 * interval until abortTimeOut is reached
 *
 * Settings -:
 * url -          the url to ajax call
 * method -       get/post (defaults to get)
 * sendData -     array of values to be passed in - 
 *                e.g. {name: "foo", something: "else"}
 * timeout -      timeout in ms between each poll (default 1000)
 * type -         json/text/xml what you are expecting as a 
 *                response (default json)
 * abortTimeOut - how long in total before we completely give up in 
 *                milliseconds (default 60000) to have no abort 
 *                timeout dont pass in abortCallBack or testCallBack
 *
 *
 * Usage -:
 *
 * 1) As a never ending poll
 * $(document).ready(function(){
 *       $.PollingWithTimeouts({
 *              url : '/foo/',
 *              sendData:  {foo: 'foo', etc: 'etc'}
 *       });
 * })
 *
 * 2) As a never ending poll with a pollCallBack (stock ticker for example)
 * $(document).ready(function(){
 *       $.PollingWithTimeouts({
 *              url : '/foo/',
 *              sendData:  {foo: 'foo', etc: 'etc'}
 *       },
 *       function(pollCallBackData) { alert(pollCallBackData); }
 *   );
 * })
 *
 * 3) As a poll with an (optional) pollCallBack that aborts after the 
 * specified time calling back to the (optional) abortCallBack
 * 
 * $(document).ready(function(){
 *       $.PollingWithTimeouts({
 *              url : '/foo/',
 *              sendData:  {foo: 'foo', etc: 'etc'},
 *              abortTimeOut: 60000
 *       },
 *       function(pollCallBackData) { alert(pollCallBackData); },
 *       function(abortCallBackData) { alert(abortCallBackData); },
 *   );
 * })
 *
 * 4) As a poll with a call back that aborts after the specified time 
 * calling back to the abort function isCompletedCallBackData allows the 
 * caller to test response data and return true if polling is complete
 *    If isCompletedCallBack is true it calls the successCallBack
 *    e.g. (and the reason I wrote it) after doing WOL on 
 * machine poll the server to ping and determine if the machine is awake. 
 * This needs to abort after a period of time.
 * $(document).ready(function(){
 *     $.PollingWithTimeouts({
 *              url : '/foo/',
 *              sendData:  {foo: 'foo', etc: 'etc'},
 *              abortTimeOut: 60000
 *     },
 *     function(pollCallBackData) { alert(pollCallBackData); },
 *     function(abortCallBackData) { alert(abortCallBackData); },
 *     function(isCompletedCallBackData) {alert(isCompletedCallBackData);},
 *     function(successCallBackData) { alert(successCallBackData); },
 *   );
 * })
 *
 * Copyright (c) 2011 UKOLN (http://www.ukoln.ac.uk)
 * Mark Dewey
 * Licensed under GPL:
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 0.9
 */

(function($) {
    $.PollingWithTimeouts = function(options, pollCallBack, 
                      abortCallBack, isCompletedCallBack, successCallBack) {

            settings = jQuery.extend({
                url: '',        // URL of ajax request
                method: 'get', // get or post
                sendData: '',   // array of values to be passed in 
                                //e.g. {name: "foo", something: "else"}
                timeout: 1000,   // timeout in milliseconds - 1 sec
                type: 'json', //or whatever else you like
                abortTimeOut: 60000  //1 min
            }, options);

                f = settings.method == 'post' 
                     || settings.method == 'POST' ? $.post : $.get;

                var abort = new Date().getTime() + settings.abortTimeOut;
                getdata();

                function getdata()
        {

                        f(settings.url, settings.sendData, function(d){

                if (abortCallBack && 
                          new Date().getTime() > abort) {
                        clearTimeout(PollingWithTimeouts);
                        abortCallBack(d);
                }
                else {
                        if (isCompletedCallBack) {
                                if (isCompletedCallBack(d)) {
                                        clearTimeout(PollingWithTimeouts);
                                        if (successCallBack) {
                                                successCallBack(d);
                                        }
                                } else {
                                        if (pollCallBack) {
                                                pollCallBack(d);
                                        }
                                        PollingWithTimeouts 
                                           = setTimeout(getdata, 
                                               settings.timeout);
                                }
                        } else {
                                if (pollCallBack) {
                                        pollCallBack(d);
                                }
                                PollingWithTimeouts = setTimeout(getdata, 
                                                         settings.timeout);
                        }
                }
            }, settings.type)
        }

        };
})(jQuery);