时间事件函数

  • setInterval() - 在给定时间的细节执行功能。它将在特定的时间间隔内重复执行代码。
  • SetTimeout() - 在给定时间等待后执行功能。

JavaScript 时间事件

如果我们想在特定的时间间隔上执行JavaScript函数或者代码,需要使用时间事件,通过该事件我们可以在特定的时间间隔上执行函数和代码。
时间事件中使用了两个函数。

如何在JavaScript中使用时间事件

JavaScript在一定时间后执行代码示例:

<html>

<head>

    <script type="text/javascript">

        var myVar;

 

        function timeStart() {
			//每1秒调用一次myTimer函数。
            myVar = setInterval(function () { myTimer() }, 1000);

        }

 

        function myTimer() {

            var d = new Date();

            var t = d.toLocaleTimeString();

            document.getElementById("test").innerHTML = t;

        }

 

        function timeStop() {

            clearInterval(myVar);

        }

    </script>

</head>

<body>

    <p>

        </p>

    <button onclick="timeStart()">

        开始计时</button>

    <button onclick=" timeStop()">

        停止计时</button>

    <span id="test"> 

     

</body>

</html>
日期:2020-04-11 23:04:37 来源:oir作者:oir