2016-07-07 99 views
0

我真的需要你的帮助。我与不同的房间聊天。当用户点击一个房间按钮时,它会显示该房间中的信息,并每2秒更新一次SetINTERVAL。如何停止“setInterval”并使用相同的功能启动另一个功能

EXAMPELE CODE:

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

的问题是,如果在其他房间BUTTON喜点击的聊天重叠。 我如何停止

VAR ABC然后用不同的值重新启动它?

HERE IS A EXAMPLE(this is just a example page):

+1

我把下面的答案,但是你应该认真考虑的WebSockets为此目的 – aximus

回答

0
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该变量;

+1

取消计时器正确的方法是使用'clearInterval(ABC)'。 – Phylogenesis

+0

@Phylogenesis你是对的,纠正 – aximus

0

如何停止的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 
}