无法运行包含两次setTimeout()的函数.奇怪的行为

Could not run function which includes setTimeout() twice. Strange behaviour

本文关键字:函数 运行 包含两 setTimeout      更新时间:2023-09-26

我有一个javascript函数setTimeout()setInterval()函数的问题。

基本上我的函数处理表单提交动作。点击"提交"按钮后,指向表单的所有数据都被序列化并通过ajax发送,ajax触发"functionName"。如果一切正常,functionName返回1,否则返回错误码。在此之后,创建了带有成功消息错误代码的弹出式div。弹出的div应该是可见的6秒。用户应该看到倒计时从60。当达到零时,如果给出了重定向参数,则页面将被重定向。如果没有指定重定向参数,则删除弹出的div。我正在使用setTimeout()函数,这会产生一些麻烦。在此之前,我使用setinterval函数,问题看起来几乎相同。

当函数 handlessubmit 第一次被触发时(提交按钮被点击),倒计时函数工作得很好,但是当我再次触发这个函数时,奇怪的事情发生了。我使用onclick来运行我的函数。

<input type="submit" name="submit" onclick="handleSubmit('formName', 'functionName', 'redirectURL')" value="send" />

下面是函数的定义:

function handleSubmit(formName, functionName, redirectLocation){
    $('form#' + formName).submit(function(event){
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: '/ajax/functions/module=none,method=' + functionName,
            data: $('form#' + formName).serialize(),
            success: function(data){
                var div = $('<div></div>').addClass('messages');
                div.appendTo('.content_block');
                var exitButton = $('<p class="title" style="overflow: hidden; margin-top:10px;"></p>');
                /**
                  * If the redirectLocation argument is empty we create HTML button with
                  * removeElement function which removes HTML popup DIV with class "messages"
                  * but if redirectLocation argument is provided we create HTML button with
                  * redirect function so after clicking we will be redirected.
                  * This buttons are created if we dont want to wait 6 seconds
                  */ 
                if(redirectLocation=='')
                    var button = $('<img title="Close this message" onclick="removeElement(''.messages'')" src="/public/images/close.png" alt="Close message" style="cursor: pointer; float: right; padding-right: 10px;" width="16" height="16"  />');
                else
                    var button = $('<img title="Close this message" onclick="redirect('''+ redirectLocation + ''')" src="/public/images/close.png" alt="Wyłącz komunikat" style="cursor: pointer; float: right; padding-right: 10px;" width="16" height="16"  />');

                exitButton.html(button);
                div.html(exitButton);
                var message = $('<p></p>');
              /**
                * Data recieved from AJAX 
                */
                if(data==1){
                    message.html("Data was successful uploaded");
                    message.appendTo(div);
                    var timer = $('<span id="timer"></span>');
                    timer.html('Message will be closed after: <b id="show-time">6</b> sec.');
                    timer.appendTo(div);
                    setTimeout("timedCount(" + redirectLocation + ")", 1000);                //this is countdown function
                }else{
                    message.html("Error: " + functionName + ".");
                    var error = $('<p>Error content: ' + data + '</p>');
                    error.appendTo(message);
                    message.appendTo(div);
                    var timer = $('<span id="timer"></span>');
                    timer.html('Message will be closed after: <b id="show-time">6</b> sek.');
                    timer.appendTo(div);
                    setTimeout("timedCount(" + redirectLocation + ")", 1000);                //this is countdown function
                }
                return true;
            }});
    });
}

我的timecount函数应该从6计数到0,看起来像这样。

  function timedCount(redirectLocation){
    timeCounter = $('#show-time').html();
    updateTime = parseInt(timeCounter)- 1;
    $("#show-time").html(updateTime);
    t = setTimeout("timedCount()", 1000);
    if(updateTime == 0){
        if(redirectLocation){
            $('#timer').html('Redirecting...');
            window.location = (redirectLocation);
        }else{
            $('.messages').remove();
            clearTimeout(t);  
        }
    }
}

总结。第一次(当不使用redirectLocation)函数 hendlessubmit 工作正常。但是当第二次点击提交按钮时,我的 timecount 函数不会从6到0倒数,并且setTimeout将在后台运行。我不知道是什么原因导致这种行为。

您正在将表单的submit事件处理程序绑定到提交按钮的click事件处理程序中。这意味着在随后的每次单击提交按钮时,将为表单的submit事件添加另一个事件处理程序。

如何声明submit事件处理程序为所有形式在一个更全局的空间?只需将$('form#' + formName).submit(function(event){...})移出handleSubmit函数:$('form').submit(function(event){...}) .

你还应该在你的setTimeout声明中使用一个匿名函数(这将避免在不必要的时候使用eval()):

setTimeout(function () {
    timedCount(redirectLocation)
}, 1000);