js Timer has the following two methods:

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

setInterval()

Syntax

setInterval(code,millisec,lang)
Parameter Description
code Required. The function to be called or the code string to be executed.
millisec Required. The time interval (in milliseconds) between each periodic execution or call of code.
lang Optional. JScript | VBScript | JavaScript

The following example executes the clock() function every 1000 milliseconds. The example also includes a button to stop the execution:

<html>
<body>

<input type="text" id="clock" />
<script type="text/javascript">
var int=self.setInterval("clock()",1000);
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()

Syntax

setTimeout(code,millisec,lang)
Parameter Description
code Required. The JavaScript code string to be called or executed.
millisec Required. The number of milliseconds to wait before executing the code.
lang Optional. The scripting language can be: JScript | VBScript | JavaScript

The following example demonstrates:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example(example.com)</title>
</head>
<body>

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

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

</body>
</html>