0

我有重置 setTimeout 的问题。我尝试使用clearTimeout()

function formMsg(text){

    if (text == "success"){
        $( ".alert-msg" ).removeClass( "hidden alert-danger" ).addClass( "alert-success" );
        $( ".alert-success .msg" ).html( "<b>Well done!</b> You successfully added order." );
    } else {
        $( ".alert-msg" ).removeClass( "hidden alert-success" ).addClass( "alert-danger" );
        $( ".alert-danger .msg" ).html( "<b>F***!</b> Something went wrong." );
    }

    window.clearTimeout(timer);

    var timer = window.setTimeout(function()
                {
                    $(".alert-msg").fadeOut("slow", function() {
                        $(this).addClass('hidden').show(0);
                    });
                }, 2000);

}

但没有结果。我希望当您单击时,计时器再次测量了两秒。

4

2 回答 2

2

那是因为您将变量初始化为本地变量(在函数内部)。这可以解决问题:

window.clearTimeout(formMsg.timer);
formMsg.timer = window.setTimeout(....)
于 2016-01-26T11:19:25.523 回答
0

将计时器移出函数上下文,如下所示:

var timer = null; //initialize    

function formMsg(text){

        if (text == "success"){
            $( ".alert-msg" ).removeClass( "hidden alert-danger" ).addClass( "alert-success" );
            $( ".alert-success .msg" ).html( "<b>Well done!</b> You successfully added order." );
        } else {
            $( ".alert-msg" ).removeClass( "hidden alert-success" ).addClass( "alert-danger" );
            $( ".alert-danger .msg" ).html( "<b>F***!</b> Something went wrong." );
        }

        if(timer !== null)
        window.clearTimeout(timer);

        var timer = window.setTimeout(function()
                    {
                        $(".alert-msg").fadeOut("slow", function() {
                            $(this).addClass('hidden').show(0);
                        });
                    }, 2000);

    }
于 2016-01-26T11:19:48.693 回答