Count lines with javascript

Asked

Viewed 1,941 times

1

I have a script where I pick up all the emails from one textarea, sending them through Ajax to another page, using the split to separate the lines. However, if you have 10 emails to send the newslast every 1s it executes and sends line by line to my Ajax, so how can I count the lines that have already been sent ?

Email Sent: 0

To every line that was sent I would like that counter increase by 1 by one until you reach the end.

HTML

    <div id="env">

            <form>

                <textarea id="email" placeholder="[email protected]"></textarea>
                <input type="button" id="execute" class="btn btn-success" value="Executar NewLast">

            </form>

            <hr>

            <div class="alert alert-dark" role="alert">
              E-Mails Enviados: 01
            </div>
            <div class="alert alert-success" role="alert">
              Enviado com sucesso para: [email protected]
            </div>

        </div><!--env-->


JS


    $("#execute").click(function(){

    var email = $("#email").val();
    var index = 0;
    splitemail = email.split("\n");

    splitemail.forEach(function(value){


        setTimeout(function(){

            $.ajax({
            url:'ajax.php',
            method:'GET',
            data: {
                email: value,
            }

            }).done(function(retorno){
                $("#ren").html(retorno);

            })

        }, 1000 * index)

        index = index + 1;
    })



}); 
  • What is the scope within your javascript of the index variable is global? Because in the setTimeout time parameter it multiplies 1000 milestones X index , for what? If you want the line count after the split just use: var qtd_lines = splitemail.length;

  • I do so because I learned this way, has any problem in my method used ? so it usually works, because it sends every 1s a new email does not send all at once the intention is not to overload the system , has something wrong with this function ? obg by the tips, another thing for example I’ve used split in var email ai when trying to eplit in var index the Cod simply to

  • Vc tah making wrong use of setTimeout. It will overload your system the same way.

2 answers

1

I see the following problems in your code:

1. foreach

The forEach is not a good one, because it will give a loop without expecting anything, ie, will call the elements of the array immediately without queuing, running everything inside continuously and directly.

2. Settimeout

The way you put it, will call Ajax every 1 second, but will not respect the processing and will send another request after 1 second, and so on, can create a bottleneck in the processing of your server.

Suggestion

Create a function that will send the requests, and each time the Ajax processing is finished, you check if there is still email in the array queue to be sent and call again the same function. Each time Ajax is processed, you increment the variable index and plays the value in <span> which I created as an accountant. If I go to explain each change in the code it will give a huge text. You can directly see what has been improved and implemented in the code:

HTML:

<div id="env">
   <form>
      <textarea id="email" placeholder="[email protected]"></textarea>
      <input type="button" id="execute" onclick="envia()" class="btn btn-success" value="Executar NewLast">
   </form>
   <hr>
   <div class="alert alert-dark" role="alert">
     E-Mails Enviados: <span id="conta">0</span>
   </div>
   <div id="ren" class="alert alert-success" role="alert">
   </div>
</div><!--env-->

Javascript:

var index = 0;
function envia(){
   var email = $("#email").val().trim();
   splitemail = email.split("\n");

   if(index < splitemail.length){

      $.ajax({
         url:'ajax.php',
         method:'GET',
         data: {
           email: splitemail[index],
         }
      }).done(function(retorno){
         index++;
         $("#ren").append('<br />'+retorno);
         $("#conta").html(index);
         setTimeout("envia()", 1000);
      });
   }
}

In ajax.php, you should return something like this:

<?php
$email = $_GET['email'];
echo 'Enviado com sucesso para: '.$email;
?>

0

I will try to give an explanation for you to understand what you did, for your answers I believe you wrote but did not understand.

The setTimeout will execute the code contained in its function, which is a callback, only after the time set in the second parameter of this function in the case below is 3000 milliseconds which corresponds to 3 seconds.

setTimeout(function(){ alert("Hello"); }, 3000);

Therefore time is defined as below :

$("#execute").click(function(){
    var email = $("#email").val();
    var index = 0;
    splitemail = email.split("\n");
    splitemail.forEach(function(value){
        setTimeout(function(){
            $.ajax({
                    url:'ajax.php',
                    method:'GET',
                    data: { email: value }
        }).done(function(retorno){
            $("#ren").html(retorno);
        })
    }, 1000 * index);
    index = index + 1;
});

is saying it is to send the request every 1000 milliseconds X index (1000 X index). But who is index, index is a variable contained in your local event scope onclick which is triggered when there is a click on the button on your form defined by the id #execute. The index variable is incremented by +1 for each interaction of your foreach which in this case is a loop defined by the amount of items contained in your array splitemail. Therefore, as the ajax request will be invoked depending on the amount of line breaks contained in your textarea at each foreach interaction will multiply 1000 milliseconds per index, in the first interaction of the loop its time will be 1000 x 0 since index is started with zero, in the second interaction of the setTimeout loop it will have the time parameter 1000 * 1 = 1 second (because index is 1), and in the third time it will have the parameter 1000 * 2 = 2 seconds, because index will be two and so on. So it won’t be a second like you said in your question and answer to my comment. With each new interaction the sending time gradually increases because it is multiplying index times 1 second.

If setTimeout will wait for the time set in the parameter this would be enough.

setTimeout(function(){
    $.ajax({
            url:'ajax.php',
            method:'GET',
            data: { email: value }
    }).done(function(retorno){
       $("#ren").html(retorno);
    })
}, 1000); 

Your question refers to how you could count the amount of items already shipped. In your routine you set and index variable, at each loop increment the variable is incremented by 1 more. So at the end of the foreach interaction of your array the total value of index will be the amount of existing items in your array splitemail. And if you want to know the total amount is as I said in comment after the split of the value contained in your textarea would just use the lenght in the array to get the total amount of messages contained in the listing.

/* Devolve a quantidade total de mensagens contidas no campo textarea
após transforma-las em uma array (uma lista) explodindo a string com o \n 
(quebra de linha) utilizando a função split */

var qtd_linhas = splitemail.length;

I built this example by printing the time value in setTimeout to better understand.

Send Routine Test

Insert line break emails into the textarea, then click RUN:

This example would be the right one, with the amount of emails sent in your div. click to test

$("#execute").click(function(){
     var email    = $("#email").val();
     var index    = 1;
     splitemail   = email.split("\n");  
     splitemail.forEach(function(value){ 
         alert("O tempo de espera é : "+(1000 * index));
         setTimeout(function(){ 
             alert(value); 
             $('#cnt_enviados').text("E-Mails Enviados: "+index); 
             index = index + 1;
         }, 1000);
     });
});

Browser other questions tagged

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