douzhuo6931 2014-12-07 09:19
浏览 116
已采纳

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);
//}

?>
  • 写回答

2条回答 默认 最新

  • dszpyf4859 2014-12-07 09:23
    关注

    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);
            }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号