1.计时方法
1)setInterval() -间隔指定的毫秒数不停地执行指定的代码
clearInterval() -停止setInterval()方法执行的函数代码
2)setTimeout() -暂停指定的毫秒数后执行指定的代码 (递归)
clearTimeOut()
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<button onclick="stopTime()">an</button>
<p id="pid"></p>
<script type="text/javascript">
var mytime = setInterval(function(){
getTime();
},1000);
function getTime(){
var d = new Date();
var t = d.toLocaleString();
document.getElementById("pid").innerHTML = t;
}
function stopTime(){
clearInterval(mytime);
}
</script>
</body>
</html><!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body onload="myWin()">
<button onclick="stopWin()">an</button>
<p id="pid"></p>
<script type="text/javascript">
var win;
function myWin(){
alert("hello");
win = setTimeout(function(){myWin()},3000);
}
function stopWin(){
clearTimeout(win);
}
</script>
</body>
</html>

本文介绍了JavaScript中的两种定时器:setInterval() 和 setTimeout() 的使用方法。setInterval() 用于每隔固定时间执行一次指定函数,可通过 clearInterval() 停止;setTimeout() 则是在指定时间后仅执行一次,可以通过 clearTimeout() 来取消执行。通过示例代码展示了如何运用这两种定时器进行网页元素的实时更新及递归调用。

被折叠的 条评论
为什么被折叠?



