
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box {
width: 40px;
height: 40px;
background: #000;
position: absolute;
}
</style>
<script type="text/javascript">
var timer;
var box;
window.onload = function() {
box = document.getElementById("box")
timer = setTimeout("move()", 10)
document.getElementById("btn").onclick = function() {
if(this.innerText == "启动") {
this.innerText = "停止"
timer = setTimeout("move()", 10)
} else {
this.innerText = "启动"
clearTimeout(timer)
}
}
}
function move() {
//距离左侧的像素每次增大
var left = parseInt(box.style.left);
if(left > 600) {
left = 50
}
console.log(left)
box.style.left = left + 1 + "px"
timer=setTimeout("move()", 10)
}
</script>
</head>
<body>
<div id="box" style="left: 50px; top: 100px;">
</div>
<button id="btn">停止</button>
<script type="text/javascript">
// setTimeout(函数,执行的毫秒数)
// 这个方法只能够执行一次
// clearTimeout()
</script>
</body>
</html>