清除一个超时,开始另一个超时

发布于 2024-12-11 10:54:06 字数 1320 浏览 0 评论 0原文

我使用 ajax/json 自动刷新网站上的内容。使用 jkey,我触发了对文档的一些发布,在此操作期间,我想取消正在运行的原始 setTimeout(在 2 分钟时“重新加载”),然后再次触发整个函数“内容”以在 5 秒后重新开始。但是,我似乎无法正确停止“重新加载”,也无法在给定的秒数后调用“内容”。有人能发现错误吗?

 <script>
$(function content(){
  function reloading(){
      $.ajax({                                      
      url: 'api.php',                          
      data: "",                      
      dataType: 'json',                    
      success: function(data)          
      {
        var id = data[0];              
          _id = id;
        var vname = data[1];           
        var message = data[2]; 
        var timestamp = data[3]; 
        var field1 = data[4]; 
        _field1 = field1;
        var val2 = parseInt(field1, 10) ;
        _val2 = val2;
        $('#output').hide().html( message ).fadeIn("slow");   
         $('#username').hide().html( vname +":" ).fadeIn("slow");
      setTimeout(reloading,120000);
 }
      });
  }
  reloading();
}); 

  $(document).jkey('a',function() {
     $.post("update.php", { "id": _id} )
      $('#output').hide().html( "<i>thx" ).fadeIn("slow");
      $('#username').fadeOut("fast");
      $('#valg1').fadeOut("fast");
      $('#valg2').fadeOut("fast");
        clearTimeout(reloading);
       setTimeout(content,5000);
      });
</script>

I'm auto-refreshing the content on a site using ajax/json. Using jkey, I trigger some posting to the document, and during this action I want to cancel the original setTimeout that's running ("reloading" at 2 mins) - and then trigger the entire function "content" again to start over after 5 secs. However, I can't seem to stop "reloading" properly, neither call "content" after the given seconds. Can anybody spot the error?

 <script>
$(function content(){
  function reloading(){
      $.ajax({                                      
      url: 'api.php',                          
      data: "",                      
      dataType: 'json',                    
      success: function(data)          
      {
        var id = data[0];              
          _id = id;
        var vname = data[1];           
        var message = data[2]; 
        var timestamp = data[3]; 
        var field1 = data[4]; 
        _field1 = field1;
        var val2 = parseInt(field1, 10) ;
        _val2 = val2;
        $('#output').hide().html( message ).fadeIn("slow");   
         $('#username').hide().html( vname +":" ).fadeIn("slow");
      setTimeout(reloading,120000);
 }
      });
  }
  reloading();
}); 

  $(document).jkey('a',function() {
     $.post("update.php", { "id": _id} )
      $('#output').hide().html( "<i>thx" ).fadeIn("slow");
      $('#username').fadeOut("fast");
      $('#valg1').fadeOut("fast");
      $('#valg2').fadeOut("fast");
        clearTimeout(reloading);
       setTimeout(content,5000);
      });
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

好菇凉咱不稀罕他 2024-12-18 10:54:06

clearTimeout 应该获取由 setTimeout 返回的唯一“key”。所以在设置时,将返回值赋给全局变量:

window["reload_timer"] = setTimeout(reloading,120000);

然后有这样的:

clearTimeout(window["reload_timer"]);

The clearTimeout should get the unique "key" that is returned by setTimeout. So when setting, assign the return value to global variable:

window["reload_timer"] = setTimeout(reloading,120000);

Then have this:

clearTimeout(window["reload_timer"]);
情何以堪。 2024-12-18 10:54:06

您必须保存 setTimeout() ID,以便稍后使用 clearTimeout() 清除它。像这样:

var timeoutID = setTimeout(function(){someFunction()}, 5000);//this will set time out
//do stuff here ...
clearTimeout(timeoutID);//this will clear the timeout - you must pass the timeoutID

You must save the setTimeout() id in order to later clear it with clearTimeout(). Like this:

var timeoutID = setTimeout(function(){someFunction()}, 5000);//this will set time out
//do stuff here ...
clearTimeout(timeoutID);//this will clear the timeout - you must pass the timeoutID
以为你会在 2024-12-18 10:54:06

除了保存其他帖子中提到的超时 ID 之外,您的函数重新加载是在函数内容内创建的,并且由于您没有创建它的闭包,因此程序的其余部分无法访问它。

$(function content(){
    function reloading(){
        console.log('RELOADING');
    }
    reloading();
}); 

// Can't reach `content` or `reloading` from here

你必须做这样的事情:

var reloading, content, reloadingTimeoutId, contentTimeoutId;


reloading = function () {
    console.log('RELOADING');
    $.ajax(
       // CODE
       success : function (data) {
           // CODE
           reloadingTimeoutId = setTimeout(reloading, 120000);
       }
    )
};


content = function () {
    reloading();
};


$(document).jkey('a',function() {
    // CODE
    clearTimeout(contentTimeoutId);
    contentTimeoutId = setTimeout(content,5000);
});

如果不了解大局,要写得更好有点困难。这样,content 将在 5 秒后被调用,只要 reloading 成功,它就会每 120 秒回调一次。请注意,重新加载永远不会以这种方式清除。

Besides saving the timeout id as mentioned in other posts, your function reloading is created inside function content and since you create no closure to it, it's unreachable from the rest of the program.

$(function content(){
    function reloading(){
        console.log('RELOADING');
    }
    reloading();
}); 

// Can't reach `content` or `reloading` from here

You have to do something like this:

var reloading, content, reloadingTimeoutId, contentTimeoutId;


reloading = function () {
    console.log('RELOADING');
    $.ajax(
       // CODE
       success : function (data) {
           // CODE
           reloadingTimeoutId = setTimeout(reloading, 120000);
       }
    )
};


content = function () {
    reloading();
};


$(document).jkey('a',function() {
    // CODE
    clearTimeout(contentTimeoutId);
    contentTimeoutId = setTimeout(content,5000);
});

It's kinda difficult writing this better not knowing the bigger picture. With this, content will be called after 5 seconds and as long as reloading succeeds it will callback itself every 120 seconds. Please observe that reloading is never cleared this way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文