My code is having infinite loop, which is wrong

Asked

Viewed 47 times

-1

My code is presenting an infinite loop, which may be wrong

Code in javascript

// Mensagens
var fromm = null, startt = 0;urll = "chat/novo.php";
$(document).ready(function(){
    //from = prompt("Daniel Usuario aqui");
    loadd();
    $('form').submit(function(e){
        $.post(urll, {
            message: $('#mensagem').val(),
            from: <?=$id?>
        });
        $('#mensagem').val('');
        return false;
    })
});

function loadd(){
    $.get(urll + '?startt=' + startt, function(resultt){
        if(resultt.itemss){
            resultt.itemss.forEach(itemm =>{
                startt = itemm.id_chat;
                $('#cli').append(renderCliente(itemm));
            });
            //$('#cli').animate({scrollTop: $('#cli')[0].scrollHeight});

        };
        loadd();
    });
}

function renderCliente(itemm){

    var nomee
    var cliente
    var dep
    nomee = itemm.nome_chatid
    cliente = itemm.nome_cliente
    dep = itemm.nome_sis


    return '<div class="msg"><p>'+itemm.id_chatid+nomee+'</p>'+cliente+'<span>'+dep+'</span></div>';
}
// Fim Mensagens

html code

<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="cli" id="cli"></div>

php code

$db = new mysqli("$host","$user","$pass","$db");
if($db->connect_error){
    die ("Connection failed: " . $db->connect_error);
}
$resultt = array();
//print menssages
$startt = isset($_GET['startt']) ? intval($_GET['startt']):0;
$itemss = $db->query("SELECT * FROM chat_ID CID LEFT JOIN colaborador CO ON CID.atendente_chatid=CO.id_pessoa LEFT JOIN cliente CL ON CID.cliente_chatid=CL.id_cliente LEFT JOIN sistemas SIS ON SIS.id_sis=CID.departamento_chatid WHERE CID.status_chatid='N' AND CID.id_chatid > ". $startt);
while($row = $itemss->fetch_assoc()){
    $resultt['itemss'][] = $row;
}


$db->close();


header('Acess-Control-Allow-Origin: *');
header('Content-Type: application/json');

echo json_encode($resultt);

1 answer

1


When the page is loaded, you end up calling the function:

$(document).ready(function(){

And within it, you make the call of function loadd, so far smoothly.

Turns out its function loadd is recursive and while the condition $.get(urll + '?startt=' + startt, function(resultt){ is true, the loadd will call itself... generating its infinite loop.


One option is to remove this recursion from the function loadd:

function loadd(){
    $.get(urll + '?startt=' + startt, function(resultt){
        if(resultt.itemss){
            resultt.itemss.forEach(itemm =>{
                startt = itemm.id_chat;
                $('#cli').append(renderCliente(itemm));
            });
            //$('#cli').animate({scrollTop: $('#cli')[0].scrollHeight});

        };
    });
}

In case you need to keep this loadd recursively, you can try to keep only the largest itemm.id_chat in the variable startt and only invoke the recursion if the startt is greater than its previous value and the API has returned data:

function loadd(){
    $.get(urll + '?startt=' + startt, function(resultt){
        if(resultt.itemss){

            //Manter o valor anterior armazenado
            let oldStartt = startt;

            resultt.itemss.forEach(itemm =>{

                //Só pegar o valor de id_chat caso seja superior
                if(itemm.id_chat > startt) {
                    startt = itemm.id_chat;
                }

                $('#cli').append(renderCliente(itemm));
            });
            //$('#cli').animate({scrollTop: $('#cli')[0].scrollHeight});

            //Só invoca a loadd caso o id anterior seja menor que o retornado
            if(startt > oldStartt) {
                loadd();
            }
        };
    });
}

I believe this is not necessary, it is more to exemplify the output of recursion, it will surely be called more than once, taking into account that variable startt starts at zero.

Browser other questions tagged

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