如何使用jQuery在等待一段时间后自动调用一个函数

如何使用jQuery在等待一段时间后自动调用一个函数

为了在等待一段时间后自动运行一个函数,我们使用jQuery delay()方法。
jQuery中的.delay()方法,用于设置一个定时器,以延迟队列中下一个项目的执行。
语法:

$(selector).delay(para1, para2);

步骤:

  • 当Button被点击时,使用.delay()方法将进程延迟到特定的时间段。
  • 函数或进程使用.queue()方法进行排队。在进程或函数被执行后,所有被执行的函数都用.dequeue()方法去排队。

示例 1:

<!DOCTYPE html>
<html>
 
<head>
    <title>How to call a function automatically
      after waiting for some time using jQuery</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js">
  </script>
    <style type="text/css">
        img {
            display: none;
        }
    </style>
</head>
 
<body>
    <center>
        <h1 style="color:green;">
        GeeksForGeeks
    </h1>
        <h3>How to call a function automatically
          after waiting for some time using jQuery</h3>
        <button type="button" class="show-image">Click</button>
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20190912174307/qwe1.png" />
        <script type="text/javascript">
            function showImg() {
                ("img").fadeIn(1500);
            }
 
            (document).ready(function() {
                (".show-image").click(function() {
                    (this).text('Wait...').delay(1000).queue(function() {
                        (this).hide();
                        showImg();
                        (this).dequeue();
 
                    });
                });
            });
 
        </script>
    </center>
</body>
 
</html>

输出:

如何使用jQuery在等待一段时间后自动调用一个函数?

例子2:伴随着警报方法

<!DOCTYPE html>
<html>
 
<head>
    <title>How to call a function automatically
      after waiting for some time using jQuerye</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js">
  </script>
    <style type="text/css">
        img {
            display: none;
        }
    </style>
</head>
 
<body>
    <center>
        <h1 style="color:green;">
        GeeksForGeeks
    </h1>
        <h3>How to call a function automatically
      after waiting for some time using jQuery</h3>
        <button type="button" class="show-image">
          Click
      </button>
        <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20190912174307/qwe1.png" />
        <script type="text/javascript">
            function showImg() {
                ("img").fadeIn(1500);
            }
            (document).ready(function() {
                (".show-image").click(function() {
                    (this).text('Wait...').delay(1000).queue(function() {
                        (this).hide();
                        showImg();
                        (this).dequeue();
                        alert("Waiting time is over");
                    });
                });
            });
        </script>
    </center>
</body>
 
</html>

输出:

如何使用jQuery在等待一段时间后自动调用一个函数?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程