How to add a delay in Javascript

posted on by - 768 views

In my early days of coding I really had some trouble finding out how to add a delay in Javascript. Using jQuery I was happy to find out the delay() function, which I thought it was perfect for my needs – turns out it wasn’t, because it is most used to set a delay for animations or jQuery effects.

You can, for example, set a delay for a fadeIn() by writing the following code:

jQuery( '#element' ).delay( 800 ).fadeIn( 400 );

…but this won’t work, for example, for the execution of a function, adding or removing a class, or things that are NOT animations.

So what can we do? The answer is pretty simple.

Using setTimeout() to add a delay in Javascript

That’s right. The most easy and straightforward way to add a delay in Javascript is using setTimeout(), which allows us to control times and delays of the things we want to execute. So, let’s suppose we have a function that shows an alert, and we want to execute that function three seconds after the page is loaded (we will use jQuery).

function showAlert(){
    alert( "Yay!" );

jQuery( document ).ready( function(){
    setTimeout( function(){
    }, 3000 )

And that’s it. With this code, once the page is loaded it will wait three seconds (note that the time is in milliseconds) and then execute our function. Of course, you can use this method with almost any type of code.