setTimeout只在循环中运行一次

My goal is to perform the javascript function every X amount of seconds. I've read that setInterval should be used but I don't believe so in my case. I also don't want the variables to have to be resent just incase the user decides to change things before everything was officially sent

For example, I put 60 in time and 5 in amount but it waited 60 seconds and then just sent 5 instead, 1 text every 60 seconds until it had sent 5 texts

my javascript

    $('input[name="sendtxt"]').click(function(e) {
        sendText(e);
    });

function sendText(e) {
    e.preventDefault();
    var phonenum = $('input[name="phonenum"]').val();
    var provider = $('select[name="provider"]').val();
    var message = $('textarea[name="message"]').val();
    var otherprov = $('input[name="otherprov"]').val();
    var amount = $('input[name="amount"]').val();
    var time = $('input[name="time"]').val() * 1000;
    var sendmsg;
    for (sendmsg = 1; sendmsg <= amount; sendmsg++) {
        setTimeout(function() {
            $.ajax({
                type: 'POST',
                data: {
                    provider: provider,
                    message: message,
                    phonenum: phonenum,
                    amount: amount,
                    otherprov: otherprov,
                    time: time
                },
                url: 'send.php',
                success: function(data) {
                    console.log('Success. Sent ' + sendmsg + " texts.");
                },
                error: function(xhr, err) {
                    console.log("readyState: " + xhr.readyState + "
status: " + xhr.status);
                    console.log("responseText: " + xhr.responseText);
                }
            });
        }, time);
    }

and my PHP

<?php


$to = $_POST["phonenum"];
$provider = $_POST["provider"];

$otherprov = $_POST["otherprov"];
$fixedotherprov = str_replace("otherprovider", "", $otherprov);


$completenum = $to . $provider . $fixedotherprov;
$completenum = str_replace('otherprovider', '', $completenum);
$subject = 'Hello';
$message = $_POST["message"];
$headers = 'From: Daniel';
$amount = $_POST["amount"];

//for ($x = 0; $x < $amount; $x++) {
    mail($completenum, $subject, $message, $headers);
//}

?>

setTimeoutis an asynchronous function. The timeout events are defined in your loop from sendmsg = 1 to sendmsg <= amount. After executing the for loop, rest of the code below the for loop is being executed until the timeout event fires. When the timeout events are fired, the value of sendmsg is equal to amount+1 as the loop is already finished execution. Therefore all the timeout events gets value of sendmsgas amout+1 leading the unexpected behaviour..

In the code below, a temporary scope is defined at each iteration which gives different sendmsg value to each timeout event.

You also have to schedule different times as the timeout time value in each iteration in order to execute them in different timeouts.

Modify your code like this..

function sendText(e) {
    e.preventDefault();
    var phonenum = $('input[name="phonenum"]').val();
    var provider = $('select[name="provider"]').val();
    var message = $('textarea[name="message"]').val();
    var otherprov = $('input[name="otherprov"]').val();
    var amount = $('input[name="amount"]').val();
    var time = $('input[name="time"]').val();
    var sendmsg;
    for (sendmsg = 1; sendmsg <= amount; sendmsg++) {
            (function(sendmsg){
               setTimeout(function() {
                $.ajax({
                    type: 'POST',
                    data: {
                        provider: provider,
                        message: message,
                        phonenum: phonenum,
                        amount: amount,
                        otherprov: otherprov,
                        time: time * 1000 * sendmsg
                    },
                    url: 'send.php',
                    success: function(data) {
                        console.log('Success. Sent ' + sendmsg + " texts.");
                    },
                    error: function(xhr, err) {
                        console.log("readyState: " + xhr.readyState + "
status: " + xhr.status);
                        console.log("responseText: " + xhr.responseText);
                    }
                });
            }, time * 1000 * sendmsg);
           })(sendmsg);
        }
}

this is a matter of scope.

read more about Javascript closure (scoped) functions: http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside

change your code to:

for (sendmsg = 1; sendmsg <= amount; sendmsg++) {
    (function(){
        setTimeout(function(_provider, _message, _phonenum, _amount, _otherprov, _time, _sendmsg) {
            $.ajax({
                type: 'POST',
                data: {
                    provider: _provider,
                    message: _message,
                    phonenum: _phonenum,
                    amount: _amount,
                    otherprov: _otherprov,
                    time: _time
                },
                url: 'send.php',
                success: function(data) {
                    console.log('Success. Sent ' + _sendmsg + " texts.");
                },
                error: function(xhr, err) {
                    console.log("readyState: " + xhr.readyState + "
status: " + xhr.status);
                    console.log("responseText: " + xhr.responseText);
                }
            });
        }, time);
    })(provider, message, phonenum, amount, otherprov, time, sendmsg);
}

hope that helps.