Search code examples
javascriptajaxprototypejs

How to change frequency of PeriodicalExecuter based on server response?


I have a reload function that reloads a page periodically. However, I would like to reload the page only if certain conditions are met (if not, increase the interval for the reload). So I tried using PeriodicalExecutor and an Ajax call like this -

<script type="text/javascript">

var nextReload = 10;

function reloadPage() {

    document.location.reload();
    return new PeriodicalExecuter(function(pe) {

       new Ajax.Request('/Task/reloadPage.htm',
      {
        method:'post', 
        parameters: { ... },
        onSuccess: function(transport) {
          var response = ... 
          nextReload = response.nextReload;           
        },
        onFailure: function(){ ... }
      });     
     this.frequency = nextReload; // doesn't do what I'd like it to do. 
    }, nextReload);    
}

var myReload = reloadPage();

</script>

As you can see, the Ajax call returns the time (in seconds) in which the next reload should occur. However, I am not able to set the frequency of the PeriodicalExecutor to nextReload.

So how can I reload the page at variable time intervals?


Solution

  • Would something like this work for you?

    <script>
    
    function tryReload(){
        new Ajax.Request('/Task/reloadPage.htm',
        {
            method:'post', 
            parameters: { ... },
            onSuccess: function(transport) {
                if(transport == seconds){
                    // call self in x seconds
                    setTimeout(tryReload, (1000*transport));
                }
                else{ // transport is a URL
                    window.location = transport;
                }
            },
            onFailure: function(){ ... }
        });
    }
    
    //start it up!
    tryReload();
    
    </script>