js定时器的用法

js 定时器有以下两个方法:

  • setInterval() :按照指定的周期(以毫秒计)来调用函数或计算表达式。方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
  • setTimeout() :在指定的毫秒数后调用函数或计算表达式。

setInterval() :

以下是实例在每 2000 毫秒执行 clock() 函数。实例中也包含了停止执行的按钮:

<html>
<body>

<input type="text" id="clock" />
<script type="text/javascript">
var int=self.setInterval("clock()",2000);
function clock()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("clock").value=t;
}
</script>

<button onclick="int=window.clearInterval(int)">停止</button>

</body>
</html>

setTimeout() :

<html>
<body>

<p>点击按钮,在等待 3 秒后弹出 "Hello"。</p>
<button onclick="myFunction()">点我</button>

<script>
function myFunction()
{
    setTimeout(function(){alert("Hello")},3000);
}
</script>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/m0_59735348/article/details/119521464