JS - how to remove setTimeOut for my code

I try to use vertical scrolling to display the object A . The idea is that if my scroll height is greater than scrollHeight (15) then after 1.2 seconds A will appear . Then, when I go back, A will hide.

The problem is, if I don't use clearTimeout, setTimeout will ignore the condition: if (scroll> = scrollHeight)

When I use clearTimeout it seems like it only works on very fast scrolls or just doesn't work.

Here is my code.

var scrollHeight = 15;

$(window).scroll(function() {
    var scroll = getCurrentScroll();
    var delayThis;

    if ( scroll >= scrollHeight ) {
        delayThis = setTimeout(function(){

        //Display **A**... 

        }, 1200);

       }
       else{
        // Hide **A** ...
        clearTimeout(delayThis);
        }
  }

      

Many thanks for the help!

+3


source to share


2 answers


You have to tell the script if the message is already displayed or not, this way you avoid multiple delays. Below is a working version of what I am talking about. Hope it helps.



var scrollHeight = 15;
var message = $( ".message" ); 
var messagestatus = false;
var scrollposition;

$(window).scroll(function() { 
    scrollposition = $(document).scrollTop();
    
    if ( scrollposition >= scrollHeight ) {
        if ( messagestatus == false ) {
            setTimeout(function(){

                message.show();
                messagestatus = true;
                
            }, 1200);
        }

    } else{
        message.hide();
        messagestatus = false;
    } 
});
      

.message {
    display: none;
    position: fixed;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>top</p>
<div class="message">
    Show!
</div>
<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 />
<p>bottom</p>
      

Run code


+1


source


You need to put delayThis outside of the event using scrollHeight. Because otherwise it no longer exists. Right now, you have it, where it is local to only one scroll event ... not to subsequent ones.



Also ... you will set the timeout over and over as you scroll. Therefore, before configuring, you probably want to make sure that delayThis is not already installed.

0


source







All Articles