Usage of js timer

The js timer has the following two methods:

  • setInterval() : Calls a function or evaluates an expression at a specified interval (in milliseconds). method will keep calling functions until clearInterval() is called or the window is closed.
  • setTimeout() : Calls a function or evaluates an expression after the specified number of milliseconds.

setInterval() :

The following is an example to execute the clock() function every 2000 milliseconds. The example also contains a button to stop execution:

<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>

Guess you like

Origin blog.csdn.net/m0_59735348/article/details/119521464