的变量:
myVar = setInterval(function, milliseconds);
clearInterval(myVar);
实例
类似上例,但是我们添加了一个“停止时间”按钮:
<p id="demo"></p>
<button onclick="clearInterval(myVar)">停止时间</button>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
完整实例:
<!DOCTYPE html>
<html>
<body>
<p>此页面上的脚本启动这个时钟:</p>
<p id="demo"></p>
<button onclick="clearInterval(myVar)">停止时间</button>
<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
更多实例
另一个简单的计时
<!DOCTYPE html>
<html>
<body>
<button onclick="timedText()">试一试</button>
<p id="demo">点击“试一试”。我将在两秒,四秒和六秒过后显示。</p>
<script>
function timedText() {
setTimeout(myTimeout1, 2000)
setTimeout(myTimeout2, 4000)
setTimeout(myTimeout3, 6000)
}
function myTimeout1() {
document.getElementById("demo").innerHTML = "2 秒";
}
function myTimeout2() {
document.getElementById("demo").innerHTML = "4 秒";
}
function myTimeout3() {
document.getElementById("demo").innerHTML = "6 秒";
}
</script>
</body>
</html>
由计时时间创建的时钟
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // 在数字 < 10 之前加零
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>