如何根据服务器响应更改PeriodicalExecuter的频率?

时间:2014-03-05 19:44:12

标签: javascript ajax prototypejs

我有一个重新加载函数,可以定期重新加载页面。但是,我想仅在满足某些条件时才重新加载页面(如果不满足,则增加重新加载的间隔)。所以我尝试使用PeriodicalExecutor和这样的Ajax调用 -

<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>

如您所见,Ajax调用返回下一次重新加载应该发生的时间(以秒为单位)。但是,我无法将PeriodicalExecutor的频率设置为nextReload

那么如何以可变的时间间隔重新加载页面?

2 个答案:

答案 0 :(得分:0)

这样的事情对你有用吗?

<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>

答案 1 :(得分:0)

基于@Rocket Hazmat的建议,这对我有用 -

function reloadPage() {

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

var that = this;

   new Ajax.Request('/Task/reloadPage.htm',
  {
    method:'post', 
    parameters: { ... },
    onSuccess: function(transport) {
      var response = ... 
      nextReload = response.nextReload; 
      that.frequency = next; 
      that.stop();
      that.registerCallback();          
    },
    onFailure: function(){ ... }
  });     



}, nextReload);    
}