Will McLean is a designer and artist working in the Central Coast of NSW where he lives with his wife and 2 children.

Will is a meticulous developer and favours simplicity and clarity within his code. He can’t stand writing things twice so searches for any way to automate. His experiments can be found in the Exercises section of this site.

Will designs within systems. No project is too small for a design system. He favours the unusual, if not, how can he progress? You can read about his work in the Case Studies section of this site.

Updated: November 1, 2017

Tags: ,

This is a Knowledge Base post.

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 );