代码编辑器:
x
1
<p>以下实例中,setInterval() 方法每 300 毫秒执行 setColor() 函数 ,该函数可以切换背景颜色</p>
2
<button onclick="stopColor()">停止切换</button>
3
<script>
4
var myVar = setInterval(function(){ setColor() }, 300);
5
function setColor() {
6
var x = document.body;
7
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
8
}
9
function stopColor() {
10
clearInterval(myVar);
11
}
12
</script>
13