功能:重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。
用法:两种颜色的切换
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>setInterval/clearInterval example</title>
<script type="text/javascript">
var nIntervId;
function changeColor() { //每一秒执行一次flashText()
nIntervId = setInterval(flashText, 500);
}
function flashText() { //颜色变化
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() { //停止颜色转换
clearInterval(nIntervId);
}
</script>
</head>
<body onload="changeColor();">
<div id="my_box">
<p>Hello World</p>
</div>
<button onclick="stopTextColor();">Stop</button>
</body>
</html>