So, I am trying to build a simple function to bring all the messages between two users. Like an chat app. I am using setInterval to refresh the messages in case some of the users inserted an new message in the database, but something it's happening: When I select a conversation, and then select another one, the function is bringing back the messages of the previous conversation for a second before showing the messages of the new selected conversation. Here it is:
// Load messages
$(".from_messages").click(function() {
$("#messageList").empty();
var from = $(this).attr('user_id');
var user = <?php echo $_SESSION['user_id']; ?>;
$("input[name='to']").val(from);
retrieve(from, user);
})
//Interval
function retrieve(from, user) {
var interval = setInterval(function() {
$("#messageList").empty();
$.ajax({
url: "server.php",
method: "post",
dataType: "json",
data: {"from": from, "user": user},
success: function(response) {
if(response != "") {
$(response).each(function(index, item) {
if(item.from_id == user) {
$("#messageList").append('<div class="col-12 text-right"><p class="w-50 ml-auto">- ' item.message '</p></div><br>');
} else {
$("#messageList").append('<div class="col-12"><p class="w-50">- ' item.message '</p></div><br>');
}
})
}
}
})
}, 3000)
}
If somebody can help me, I would be eternally grateful. And here is a link that I hope could show what I am facing: Video demostration
CodePudding user response:
setInterval(f, n)
will fire f
every n
milliseconds until you clear the interval. When you call setInterval
, it returns a reference to the interval. Save that reference and call clearInterval(reference)
when you want the interval to stop--in this case before creating a new interval when you select a different conversation.