定时器
延迟执行 ,周期执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>延迟执行</title>
</head>
<body>
<script>
console.log('this is mseeage');
var t =setTimeout(function () {
console.log('this is a setTimeout');
},1234)
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>周期执行</title>
</head>
<body>
<script>
console.log('this is message...');
(function fun() {
console.log('this is interval...');
setTimeout(fun, 1);
})();
console.log('this is message too...');
</script>
</body>
</html>
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态显示时间</title>
</head>
<body>
<button id="start">开始显示</button>
<button id="stop">停止显示</button>
<h2 id="showtime"></h2>
<script>
var t;
var start =document.getElementById('start');
start.addEventListener('click',showTime);
var stop=document.getElementById('stop');
stop.addEventListener('click',function () {
clearTimeout(t);
start.removeAttribute('disabled');
});
function showTime(){
start.setAttribute('disabled','disabled');
var date=new Date();
var hour =date.getHours();
var minute =date.getMinutes();
var second =date.getSeconds();
var time =hour+':'+minute+':'+second;
var showtime=document.getElementById('showtime');
showtime.textContent=time;
t=setTimeout(showTime,1000);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>方块自动移动</title>
<style>
body{
margin: 0;
}
#box{
width: 50px;
height: 50px;
background-color: yellow;
position: absolute;
top: 300px;
left: 100px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box =document.getElementById('box');
box.addEventListener('click',isMove);
var flag=false;
var t;
function isMove(){
if (!flag){
flag=true;
move();
}else {
flag=false;
stop();
}
}
function move() {
var style = window.getComputedStyle(box);
var left = parseInt(style.left);
left++;
box.style.left = left + 'px';
t = setTimeout(move, 5);
}
function stop() {
clearTimeout(t)
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>小球垂直移动</title>
<style>
body {
margin: 0;
}
.box {
width: 50px;
height: 50px;
background-color: lightcoral;
border-radius: 25px;
position: absolute;
left: 400px;
top: -50px;
}
</style>
</head>
<body>
<script>
var body = document.body;
const WIDTH = window.innerWidth;
function createBox(){
var div = document.createElement('div');
div.setAttribute('class','box');
var random = Math.random() * (WIDTH - 50);
div.style.left = random + 'px';
body.appendChild(div);
}
function moveDown(){
var boxs = document.getElementsByClassName('box');
for (var i=0; i<boxs.length; i++) {
var box = boxs[i];
var style = window.getComputedStyle(box);
var boxTop = parseInt(style.top);
boxTop += 10;
box.style.top = boxTop + 'px';
}
}
for (var i=0; i<10; i++) {
createBox();
}
setInterval(function(){
moveDown();
},500);
</script>
</body>
</html>