jQuery Delay()

The jQuery delay() method introduces a delay before the execution of the next function in the queue. It is commonly used in conjunction with animation methods to create timed effects.

Key Topics

Basic Usage of delay()

The delay() method pauses the execution of subsequent functions in the queue for the specified duration (in milliseconds).

$("#box").fadeOut().delay(1000).fadeIn();

Explanation: This code fades out the element with the ID box, waits for 1 second (1000 milliseconds), and then fades it back in.

Chaining with delay()

Using delay() with chained animations allows for creating timed sequences of effects.

$("#box").slideUp().delay(500).slideDown();

Explanation: This code slides up the element with the ID box, waits for 500 milliseconds, and then slides it back down.

Example: Using delay()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Delay Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="box" style="width: 100px; height: 100px; background-color: red;"></div>
    <button id="animateButton">Start Animation</button>

    <script>
        $(document).ready(function() {
            $("#animateButton").click(function() {
                $("#box")
                    .fadeOut(500)
                    .delay(1000)
                    .fadeIn(500);
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to use delay() to pause the animation of a red box for 1 second before continuing with the next animation.

Key Takeaways

  • Timed Effects: Use delay() to pause the execution of chained methods for a specified duration.
  • Animation Sequences: Combine delay() with animation methods like fadeIn() and slideUp() for smoother visual effects.
  • Event-Based Timing: Dynamically apply delays based on user interactions or events.