Menu Close

How to use jQuery setTimeout function?

Use jQuery setTimeout function

If you want to delay your jQuery code to run after some amount of time, you can use JavaScript setTimeout function to delay the execution. setTimeout is used in JavaScript to delay execution of some code and the same function can be use with jQuery without any extra effort.

The setTimeout function takes the times in miliseconds. And the block can contain either your jQuery code, or you can also make a call to any function.

Example 1: if I want to make div element fade out then you can use below code. It will fade out the div with id “settime” after 2 seconds.

$(document).ready(function(){ 
    setTimeout(function(){ 
        $('#settime').fadeOut();}, 2000); 
}); 

Example 2: with button click

$(document).ready(function() { 
    $("#btnfade").bind("click",function() {
      setTimeout(function() { 
        $('#settime').fadeOut();}, 2000); 
  });
}); 

Note: Complete code after Add jQuery To HTML.

<!DOCTYPE html>
<html> 
    <head>
        <title>settime</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    </head>  
    <body>
        <section>
            <div class="container text-center">
                <h1>settime</h1>
                <div style="padding:20px;border:1px solid #888;width: 300px;margin:20px auto;">
                    <button class="btn btn-primary" id="btnfade">Hide a Tag</button><br>
                    <a id="settime" href="https://codeamend.com/">Demo Link</a>
                </div>
            </div>
        </section>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(function() { 
                $("#btnfade").bind("click",function() {
                  setTimeout(function() { 
                    $('#settime').fadeOut();}, 2000); 
              });
            });
        </script>
    </body>
</html> 
Posted in jQuery

You can also read...