Stop a function that has been started with javascript’s setTimeout() function

I created a scroll animation that I wanted to happen 3 seconds after the page had loaded. So I used the javascript setTimeout() function:

var scrollToContent = function() {
    var element = '#my-element';
    var elementOffset = $( element ).offset().top;

    $("html, body").animate( { scrollTop: elementOffset }, 1000 );

var initScroll = setTimeout( scrollToContent, 3000 );

However I wanted the function to stop if the user starts interacting with the page (ie. scrolling or clicking on things). To do this I used the clearTimeout() function:

// Write a function to stop initScroll
var stopScrollToContent = function() {
  clearTimeout( initScroll );

// Trigger stopScrollToContent when user clicks or scrolls
$( 'body' ).click( stopScrollToContent );
$( window ).scroll( stopScrollToContent );

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s