如何停止“setInterval”并使用相同的FUNCTION启动另一个

How to stop a "setInterval" and start a other with the same FUNCTION

本文关键字:FUNCTION 另一个 启动 何停止 setInterval      更新时间:2023-09-26

我真的需要你的帮助。我和不同的房间聊天。当用户单击"房间"按钮时,它会显示该房间上的消息,并每 2 秒更新一次 SetINTERVAL。

示例代码:

var abc = setInterval(function()
    { 
        $.ajax({
          type:"post",
          url:"logs.php?user_profil=<?php echo $user_profil;?>&user=<?php echo $user;?>",
          datatype:"html",
          success:function(data)
          {
             $("#chatlogs").html(data);
          }
        });
    }, 2000);

问题是,如果嗨点击另一个房间按钮,聊天会重叠。我怎样才能停止

VAR ABC 并用不同的值重新开始?

这是一个示例(这只是一个示例页面):

var myMethod = function() {
    $.ajax({
      type: "post",
      url: "logs.php?user_profil=<?php echo $user_profil;?>&user=<?php echo $user;?>",
      datatype: "html",
      success: function(data) {
        $("#chatlogs").html(data);
      }
    });
  },
  abc = setInterval(myMethod, 2000);
clearInterval(abc);
abc = setInterval(myMethod, 2000);

说明:将回调方法保存到变量中,并将该变量重用于 setInterval;

如何停止 VAR ABC 并使用不同的值重新启动它

顺便说一下,abc变量只保存该特定间隔的 id。你真的不需要(也不能)"重新开始",你需要:)开始另一个

我会这样做:

var getRoomUpdater = (function(){
    var _userProfileId;
    var updater = function() {
        $.ajax({
            type: "post",
            url: "logs.php?user_profil=" + _userProfileId + "&user=<?php echo $user;?>",
            datatype: "html",
            success: function(data) {
                $("#chatlogs").html(data);
            }
        });
    }
    return function(userProfileId){
        _userProfileId = userProfileId;
        return updater;
    };
})();
// it will hold interval id
var abc;

// Opening a room:
var openRoom = function(roomId){
    // start automatic update
    clearInterval(abc);
    abc = setInterval(getRoomUpdater(roomId));

    // + other actions if needed
}