problem with setinterval

Asked

Viewed 42 times

0

I’m having a problem in a chat I’m developing, it works so on the right I have a contact list for me to start chat and that list is within a function carregarContatos() that is inside setInterval().

To update this contact list by clicking on a contact I step one idChat to another function abrirConversa(idChat) that feeds a DIV that will bring me the conversations of that idChat passed as parameter.

The problem is I used the setInterval() to keep recharging my messages from the conversation, then when I click on another contact to open another conversation, the old conversation is not cleaned and ends up being added with the new conversation that I opened, staying flashing the screen alternating between the two conversations and so on, if I click on a third contact adds his conversation also there is showing the 3 conversations flashing screen.

  // monta a linha na tabela apos um novo produto ter sido cadastrado
function montarLinhaContatos(c){
  let linha = "<li>" +
        "<a href='javascript:void(0)' onclick='abrirConversa("+c.ID_CHAT+")'><img src='"+c.FOTO+"' alt='user-img' class='img-circle'> <span>" + c.NOME + "<small class='text-success'>online</small></span></a>"+
        "</li>";
    return linha;                            
}

// chama a api que carregas os dados dos produtos cadastrados via objeto json
function carregarContatos(){
    $('#msg').html('carregando contatos...');
    $.getJSON('/carregarContato', function(contatos){
            $('#msg').hide();
            $('#lista-contatos').html('');
            for (let i = 0; i < contatos.length; i++) {
                linhaContato = montarLinhaContatos(contatos[i]);
                $('#lista-contatos').append(linhaContato);
            }
    });
}
function montarConversaRecebida(mr){
    let linhaMsg = "<li>" +
    "<div class='chat-image'> <img alt='male' src='"+mr.FOTO+"'> </div>"+
    "<div class='chat-body'>"+
        "<div class='chat-text'>"+
            "<h4>"+mr.NOME+"</h4>"+
            "<p>"+mr.CONTEUDO+"</p>"+
            "<b>10.00 am</b> </div>"+
        "</div>"+
    "</li>";
    return linhaMsg;
}

function montarConversaEnviada(me){
    let linhaMsg1 = "<li class='odd'>" +
    "<div class='chat-image'> <img alt='male' src='"+me.FOTO+"'> </div>"+
    "<div class='chat-body'>"+
        "<div class='chat-text'>"+
            "<h4>"+me.NOME+"</h4>"+
            "<p>"+me.CONTEUDO+"</p>"+
            "<b>10.00 am</b> </div>"+
        "</div>"+
    "</li>";
    return linhaMsg1;
}

function abrirConversa(id) {
    setInterval(function(){
        $('#alertaC').html('Carregando conversa...');
        $('#mensagens').html('');
        $.ajax({
            type: 'GET',
            url: 'carregarMensagem/'+id,
            dataType: "json",
            success: function (data) {
                $('#alertaC').html('');
                $('#mensagens').html('');
                    for (var i = 0; i < data.length; i++) {
                        linhaMsg1 = montarConversaRecebida(data[i]);
                        linhaMsg2 = montarConversaEnviada(data[i]);

                        if(data[i].CODG_USUARIO == data[i].CODG_USUARIO_DESTINATARIO){
                            $('#mensagens').append(linhaMsg2);
                        } else {
                            $('#mensagens').append(linhaMsg1);
                        }
                    }
            }
        });
    }, 500);
} 

$(function(){

    setInterval(() => {
        carregarContatos();
    }, 3000);
})
  • Do not use setInterval with Ajax, use setTimeout. Maybe tb vc is repeating id’s, no?

  • I think not because every click I pass a different id, there in my function montanha contact I call on onclick openConversa(idchat) passing the chat id

  • Would you have an example with this timeout ? because I’ve never done anything like this...

  • 1

    I’ve posted several answers with this setInterval problem. Basically you would put Ajax inside a function, call that function, and in Success call the function again. This creates a loop where Ajax is only called when Ajax is processed. When using setInterval, you will call Ajax over and over again, it is ok, but this can cause a bottleneck in the browser because a request can be called before the previous one has been completed. This can even lock the browser. With setTimeout this cannot happen pq each request will be called in order.

  • 1

    I’ll leave this article by John Resig which explains very well the use of setInterval and setTimeout in those cases... Basically, if your code setInterval take longer than the interval between one run and the other, the stack will grow infinitely and your browser will stop working.

  • So it is only within the success of my function to open Versa(id) in the success of my ajax I call my own function ? and change the setinterval for the setTimeout

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.