Search code examples
javascriptjquerycleartimeout

How to cancel function using clearTimeout()?


How to cancel function using clearTimeout() when stay bottom page less than 4 sec.?

When stay at bottom page 4 sec, will alert, it's OK ^^

But when stay at bottom page less than 4 sec, then scroll to top page, Why it's will be alert too

<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<script>
$(window).scroll(function(){
    var height = $('#idpage').height();
    var scroll_top = $(this).scrollTop();

    if(($(window).scrollTop() + $(window).height() == $(document).height())){
        var timer = setTimeout(function() {
            alert("bottom");   
        }, 4000);
    }
    else{
        clearTimeout(timer);
    }
});
</script>

Solution

  • You have declared timer as a local variable so every time the scroll handler is called a new variable reference is used. Instead you need to preserve the value of the previous timer so you need to declare the variable outside the scope of the scroll handler like

    var timer;
    $(window).scroll(function () {
        var height = $('#idpage').height();
        var scroll_top = $(this).scrollTop();
    
        if (($(window).scrollTop() + $(window).height() == $(document).height())) {
            timer = setTimeout(function () {
                alert("bottom");
            }, 4000);
        } else {
            clearTimeout(timer);
        }
    });