Search code examples
javascriptjqueryajaxcountdownlatch

jQuery Countdown plugin and AJAX


I'm using jQuery Countdown plugin to implement a Countdown and call a webservice when timer expires.

The problem is that I'm using AJAX on the page, and have to re-setup the Countdown on every AJAX request like so:

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(SetupTimer);

/*Initial setup*/
$(document).ready(function() {
    SetupTimer();
});

function SetupTimer() {
        var serverTime = new Date();
        var cutoffTime = new Date($("#<%= cutoffTime.ClientID %>").val());
        serverTime.setHours(serverTime.getHours());
        if (serverTime < cutoffTime) {
            $('#timer').countdown('destroy'); /*should work, but doesn't*/
            $('#timer').countdown({ until: cutoffTime, serverTime: serverTime, onExpiry: OrderingEnded, format: 'yowdHMS' });
        } 
        else
            OrderingEnded();
    }

This, for some reason, creates a new instance of the Countdown on ever request, resulting in numerous calls to Webservice when Countdown expires.

How do I make sure that only one instance of the Countdown exists at a time?

EDIT

found this in documentation, doesn't do it for me though

        $('#timer').countdown('destroy');

Solution

  • ok, figured it out, just needed to call the

    $('#timer').countdown('destroy');
    

    on beginRequest

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(DeleteTimer);
    prm.add_endRequest(SetupTimer);
    
    $(document).ready(function() {
        SetupTimer();
    });
    
    
    function DeleteTimer() {
        $('#timer').countdown('destroy');
    }
    function SetupTimer() {
        var serverTime = new Date();
        var cutoffTime = new Date($("#<%= cutoffTime.ClientID %>").val());
        serverTime.setHours(serverTime.getHours());
        if (serverTime < cutoffTime) {          
            $('#timer').countdown({ until: cutoffTime, serverTime: serverTime, onExpiry: OrderingEnded, format: 'yowdHMS' });
        } 
        else
            OrderingEnded();
    }