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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)