简体   繁体   中英

clearTimeout when a function gets called multiple times

I have an alert message bar that slides down when the user clicks a specific link. The alert bar slides back up after a specified period. If the user clicks this link multiple times, I would like to reset the timer, slide the alert bar back up and then slide it down again (reseting the timer).

$(document).ready(function(){

    $('#main_container').live('click', function(){
        $('.answer_yes').click (function(){


            if ($('#topbar_alert').is(':visible')){

                clearTimeout(slideUpTimer)  

                }

                $('#topbar_alert').slideDown(300);
                $('#topbar_alert_container').empty();
                $('#topbar_alert_container').append('Alert Created!');

                var slideUpTimer = setTimeout(function() {
                    $('#topbar_alert').slideUp(300);
                },8000);

        });
    });

}); 

So everything works except the clearTimeout portion. If you click the link, the alert bar slides down and then slides back up after the setTimeout finishes. But if you click the link multiple times, it doesn't reset the alert bar.

you should define the var slideUpTimer outside the current scope

var slideUpTimer;
$('#main_container').live('click', function(){
    $('.answer_yes').click (function(){
        if ($('#topbar_alert').is(':visible')){
            clearTimeout(slideUpTimer)  
        }

        $('#topbar_alert').slideDown(300);
        $('#topbar_alert_container').empty();
        $('#topbar_alert_container').append('Alert Created!');

        slideUpTimer = setTimeout(function() {
            $('#topbar_alert').slideUp(300);
        },8000);
    });
});

when you use var slideUpTimer inside the function, it only exists for that one execution, it does not persist.

To use slideUpTimer as you want to, you'll need to put it in the global scope.

var slideUpTimer;
$(document).ready....

then assign it with

slideUpTimer = setTimeout()...

notice the lack of var when assigning.

You should declare slideUpTimer outside your function. Make it global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM