Problems with setInterval

Asked

Viewed 179 times

3

Next, my problem is like this, I’m making an Inbox, so I need to update every 5s the messages. So far so good. In the div that loads the messages I put the following script:

function loadInbox1(id) {
 $("#load-inbox-1").html("<i class='fa fa-spin fa-cog'></i>");

 var timeout;
 clearInterval(timeout);

 setTimeout(function(){
      $('#load-inbox-1').load("/inbox-prof-load.php?from="+id);

        var timeout = setInterval(reloadChat, 5000);    
        function reloadChat () {
             $('#inbox-prof-load-msg').load('inbox-prof-load-msg.php?from='+id);
        }
 }, 500)

}

There where I am printing the user_id is the user I am talking to. then it loads the chat every 5s in my div. ate ai ta tranquilo. however if I click on another window that clicks on that same div another chat, the old script does not stop running and a new one also starts, causing that keeps appearing the two conversations quickly and keeps changing, if I click more it does not for the script and continues running several.

How can I do when clicking another chat stop running with this old user_id and just run a script with the new one?


First page the user chooses which Inbox he wants to open

<div class="panel panel-default">
<div class="panel-heading">
    <h4 class="panel-title">
    Mensagens dos meus alunos
    </h4>
</div>

        <div class="panel-column panel-inbox no-margin">
            <div class="row no-margin">
                <div class="col-md-5 col-sm-3 col-xs-2 panel-sidebar">
                    <ul class="media-list no-margin" id="inbox-prof-alunos">

                        <?php do { ?>
                        <li class="media <?php if ($row_inbox['inbox_new'] != 0) { echo "active"; } ?>" href="javascript:func()" onclick="loadInbox1('<?=$row_inbox['user_id']?>')">
                            <div class="col-md-11 col-sm-11 no-padding">
                                <div class="media-left">
                                    <img class="media-object img-circle" src="/images/user/avatar/<?=utf8_encode($row_inbox['user_avatar'])?>" alt="Weeazy - <?=utf8_encode($row_inbox['user_nome'])?> <?=utf8_encode($row_inbox['user_sobre_nome'])?>">
                                </div>
                                <div class="media-body hidden-xs">
                                    <h4 class="media-heading"><?=utf8_encode($row_inbox['user_nome'])?> <?=utf8_encode($row_inbox['user_sobre_nome'])?></h4>
                                    <p class="inbox-preview"><?=substr(utf8_encode($row_inbox['user_inbox_msg']), 0, 35)?><?php if (strlen($row_inbox['user_inbox_msg']) > 35) { echo "..."; } ?></p>
                                </div>
                            </div>
                        </li>
                        <?php } while($row_inbox = mysql_fetch_assoc($Busca_inbox)); ?>

                    </ul>
                </div>

                <div class="col-md-7 col-md-offset-5 col-sm-9 col-sm-offset-3 col-xs-offset-2 panel-content">
                    <div class="inner" id="load-inbox-1">

                        <div class="media-header">
                            <div class="row">
                                <div class="col-md-12 media-header-meta">
                                    <span class="text-title"><i class="fa fa-comments"></i> Clique em uma conversa para expandir</span> 
                                </div>
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </div>


</div>

Script of this page:

function loadInbox1(id) {
 $("#load-inbox-1").html("<i class='fa fa-spin fa-cog'></i>");

 var timeout;
 clearInterval(timeout);

 setTimeout(function(){
      $('#load-inbox-1').load("/inbox-prof-load.php?from="+id);

        var timeout = setInterval(reloadChat, 5000);    
        function reloadChat () {
             $('#inbox-prof-load-msg').load('inbox-prof-load-msg.php?from='+id);
        } }, 500) }

Now the page that is loaded:

                            <div class="media-header">
                            <div class="row">
                                <div class="col-md-8 col-sm-9 col-xs-9 media-header-meta">
                                    <span class="text-title">Conversa com</span> 
                                    <ul class="list-inline no-margin">
                                        <li>
                                            <h4>
                                                <a href="/profile/aluno/<?=$row_inbox['user_url']?>"><?=$row_inbox['user_nome']?> <?=$row_inbox['user_sobre_nome']?></a>
                                            </h4>
                                        </li>
                                    </ul>
                                </div>

                            </div>
                        </div>
                        <div class="message-body">

                            <div id="inbox-prof-load-msg" class="message-content row nice-scroll">

                                <?php do { ?>

                                <div class="col-md-10" <?php if ($row_inbox['user_inbox_from'] == $user_id) { echo 'style="float:right;"'; } ?>>
                                    <span class="message-box message-<?php if ($row_inbox['user_inbox_from'] == $user_id) { echo 'mine'; } else { echo 'other'; }?>" data-toggle="tooltip" data-placement="<?php if ($row_inbox['user_inbox_from'] == $user_id) { echo 'left'; } else { echo 'right'; }?>" title="<?=date('H:i', strtotime($row_inbox['user_inbox_date']))?>">
                                    <?=nl2br(utf8_encode($row_inbox['user_inbox_msg']))?>
                                    </span>
                                </div>

                                <?php } while ($row_inbox = mysql_fetch_assoc($Busca_inbox)); ?>

                            </div>



                            <div id="reply" class="reply">
                                <form class="text-right" id="profile-add-inbox">
                                    <textarea class="form-control" name="msg" placeholder="Escreva sua mensagem aqui" style="height:80px;border-bottom: 1px solid #ddd;"></textarea> 
                                    <input type="hidden" name="to" value="<?=$other_id?>">
                                    <input type="hidden" name="aluno" value="<?=$other_id?>">

                                    <button type="submit" class="btn btn-warning">Enviar</button>
                                </form>
                            </div>
                        </div>

This page that is loaded that needs to be reloaded receiving as GET that from

1 answer

2


The problem is that every click you make opens a new chat window and starts an ajax loop. If you click on people you will have 3 requests running, all changing the content of the same div that is common.

I suggest you have in Javascript something always running (in the example is the function loader() {), and each new chat window change only the ID that is searched.

 var pooler = (function() {
     var running = false;
     function loader() {
         if (!window.chatID) return;
         running = true;
         $('#inbox-prof-load-msg').load('inbox-prof-load-msg.php?from=' + window.chatID, function() {
             setTimeout(loader, 5000); // quando tiver carregado, pedir novo conteudo dentro de 5 segundos
         });
     }
     return function() {
         if (!running) loader(); // impedir multiplas execuções ao mesmo tempo
     }
 })();

 function loadInbox1(id) {
     window.chatID = id; // para saber qual a janela/chat aberta
     $("#load-inbox-1").html("<i class='fa fa-spin fa-cog'></i>");
     $('#load-inbox-1').load("/inbox-prof-load.php?from=" + id, function(){
        $('#inbox-prof-load-msg').html(''); // limpar a janela
        pooler(); // chamar o pooler
     });
 }
  • 1

    I don’t know what magic was done (rsrs) but now it worked! I’m really grateful for the help and the attention!

  • @Leonardocarmo joined explanations in the answer.

Browser other questions tagged

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