Search code examples
javascriptsettimeoutcleartimeout

Reset setTimeout


I have problem with reset setTimeout. I tried use 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);

}

but with no result. I expect that when you click, the timer has measured two seconds again.


Solution

  • That is because you initialize the variable as local (inside your function). This will do the trick:

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