How to Use jQuery’s .delay() Method

jQuery's .delay() method is one that can be used, probably quite obviously, to delay code from being executed. In particular, it can be used to make certain actions or animations last longer because the code is delayed. As a developer, there are a bunch of different reasons that you might want to use a delay. Maybe you want things to load or animate a certain amount of time after a page load or an event trigger. Using this method is also a really easy way to have something happen, have a short delay, and then go back to the way that it was.

For example, if you want a div to hide after a certain trigger event and then show again after a certain delay, you would use the delay method in a similar context to the way its used in the snippet below:

$("div").click(function{
    $(this).hide().delay(5000).show();
})

So in the snippet above, the div will be hidden after you click it for 5000 milliseconds (5 seconds) and then after the 5000 ms delay, it will appear again. The first line with the .click() method is the trigger event, which is followed by a function that executes the hide/delay/show events. So the div is hidden, then there is a 5 second delay where no code is executed, and then it is shown again.

This is just one example of how to use this versatile method. The speed parameters taken by the method (in the example above it's "5000) can either be a number value (in milliseconds) or a fixed value (slow or fast). This is quite important, as it determines the length of time of the delay and, in the example above, the duration of the hide/show effect. Remember when using number values that the time is measured in milliseconds, so multiply the amount of seconds you want the delay to last by 1000 to be sure that you've got the right time.



Responsive Menu
Add more content here...