Problem with setInterval ()

1

So folks .. I have a code that puts a setInterval of the messages passed between users de and para in the function below ..

    function openWidChat(de,para) {
        var url_s = $("#url_s").val();
        $("label#boxC input").val('');
        $("label#boxC input").removeAttr('disabled');
        $("label#boxC input").attr('user-de',de);
        $("label#boxC input").attr('user-para',para);

        $("#mensChat div._5chat").fadeIn(400).html('<div class="maxWid_16"><img src="'+ url_s +'/themes/4space/images/load/loadLikesW.gif" alt="" width="16" height="16"></div>');
        para = setInterval(function() {
            $.ajax({
                url: url_s +"/demo/chat/chat.php",
                data:'d='+de+'&p='+para+'&url_s='+url_s,
                type: "POST",
                cache: false,
                success : function(html){
                    $("#mensChat div._5chat").html(html);
                }
            });
        }, 1000);
    }

Until then it works fine, but when I click on another user's name to start in the same box a new conversation, the setInterval is going back and forth on all the users that I clicked to chat ... It gets a go and come on damn ..

Does anyone have a solution for this?

    
asked by anonymous 08.07.2015 / 19:19

1 answer

1

Talk to me,

Look, you need to put in your program a structure that uses the "clearInterval" command. The setInterval is an infinite loop, and will only stop when you ask it to stop, for example:

var looper = setInterval(function(){},1000); //Loop de 1s

clearInterval( looper ); //Para o loop.

You need to associate the function with a variable to keep track of it, which in your case is the "to" variable. At some point in your program (such as when you change the user) you will need to clearInterval like this:

clearInteval( para );

Then it will be necessary to restart the loop.

I have an answer here that can help you create a code structure.

Looking at your code, I also advise you to study a guy named "websockets" . It's something more complex, but it will help you understand more important concepts such as "pooling request", for example, but it fits into that kind of program you have there.

I hope I have helped! Hugs!

    
09.07.2015 / 13:52