Problem with setInterval()

Asked

Viewed 142 times

1

Come on, guys. I have a code that brings a setInterval of 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 a name of another user to start in the same box a new conversation setInterval keeps going back and forth on all the users that I clicked to talk to... It gets a hell of a lot..

Someone has a solution to this?

  • A problem, you have the parameter para and a variable para. That’s trouble because you’re using para in the Ajax call. In addition, you should start the variable para with var para .... I suggest that different names between the parameter and the variable.

1 answer

1

Speak my,

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 (like when you change user) you will need to put the clearInterval thus:

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 like "pooling request", for example, but it fits in this type of program that you have there.

I hope I helped! Hugs!

Browser other questions tagged

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