重置设置超时

Reset setTimeout

我对重置 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);

}

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

那是因为您将变量初始化为本地变量(在您的函数内)。 这将达到目的:

window.clearTimeout(formMsg.timer);
formMsg.timer = window.setTimeout(....)

像这样将计时器移出函数上下文:

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

    }